Create empty array with length from variable

I want to read a custom number of bytes from TcpStream

, but I cannot initialize a new empty array buffer where I can determine the length with a variable. Cannot use vector because the read function TcpStream

requires an array.

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

      

When I replace 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 this?

+3


source to share


1 answer


Use Vec with with_capacity () :

use std::net::TcpStream;

fn main() {
    use std::io::Read;

    let mut stream = TcpStream::connect("127.0.0.1:34254").unwrap();
    let mut v = Vec::with_capacity(128);

    let _ = stream.read(&mut v);
}

      



You are mixing array and slice. There are different in Rust: a slice is an in-memory representation previously defined by an array, a Vec, or whatever.

+4


source







All Articles