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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With