Create empty array with a length from a variable

Viewed 16985

I want to read a custom amount of bytes from a TcpStream, but I cannot initialize a new empty array buffer where I can define the length with a variable. It is not possible to use a vector because the TcpStream read function requires an array.

let mut buffer = [0; 1024]; // The 1024 should be a variable

When I replace the 1024 with a variable:

let length = 2000;
let mut buffer = [0; length];

I get the message:

error[E0435]: attempt to use a non-constant value in a constant
--> src/network/mod.rs:26:30
|
26 |         let mut buffer = [0; bytes];
|                              ^^^^^ non-constant used with constant

Why can't I do that?

1 Answers
Related