Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create empty array with a length from a variable [duplicate]

Tags:

rust

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?

like image 430
Daniel O Avatar asked Jun 30 '17 13:06

Daniel O


1 Answers

Use a 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 confound array and slice. There are different in Rust: a slice is a view on the memory, previously set with an array, a Vec or whatever.

like image 187
Boiethios Avatar answered Sep 20 '22 04:09

Boiethios