I’m trying to create a msg_bytes buffer to store data. But when creating it I get a type mismatch error.
use libflate::gzip::Decoder;
let mut f = std::fs::File::open("./20181002.bytes").unwrap();
let mut decoder = Decoder::new(&f).unwrap();
let mut msglen_bytes = [0u8; 4];
decoder.read_exact(&mut msglen_bytes).unwrap();
println!("msglen_bytes: {:?}", &msglen_bytes);
let length = u32::from_le_bytes(msglen_bytes);
let length_us = usize::try_from(length).unwrap();
println!("length: {}", length);
let mut msg_bytes = vec!(0u8, length_us, length_us);
let mut msg_bytes = [0u8; length_us]; // Option 2
decoder.read_exact(&mut msg_bytes).unwrap();
error[E0308]: mismatched types
--> src/main.rs:50:35
|
50 | let mut msg_bytes = vec!(0u8, length_us, length_us);
| ^^^^^^^^^ expected `u8`, found `usize`
If I run with Option 2 I get:
error[E0435]: attempt to use a non-constant value in a constant
--> src/main.rs:51:31
|
47 | let length_us = usize::try_from(length).unwrap();
| ------------- help: consider using `const` instead of `let`: `const length_us`
...
51 | let mut msg_bytes = [0u8; length_us];
| ^^^^^^^^^ non-constant value
>Solution :
You probably want let msg_bytes = vec![0u8; length_us] (note semicolon between 0u8 and the length).
vec!(0u8, length_us, length_us) attempts to create a 3-element vector whose elements have values 0u8, length_us, and length_us respectively. Since all vector elements must be of the same type, that syntax can’t compile.
Option 2 doesn’t compile because arrays must have sizes determined at compile time.