How can I copy, or reference a slice of bytes from a larger array?
I only need to read them, but I want the size to be specified to catch errors at compile-time.
let foo = rand::thread_rng().gen::<[u8; 32]>();
let bar: [u8; 16] = foo[0..16];
let baz: &[u8; 16] = &foo[16..32];
The errors are:
error[E0308]: mismatched types
--> src/main.rs:64:22
|
64 | let bar: [u8; 16] = foo[0..16];
| -------- ^^^^^^^^^^ expected array `[u8; 16]`, found slice `[u8]`
| |
| expected due to this
error[E0308]: mismatched types
--> src/main.rs:65:23
|
65 | let baz: &[u8; 16] = &foo[16..32];
| --------- ^^^^^^^^^^^^ expected array `[u8; 16]`, found slice `[u8]`
| |
| expected due to this
|
= note: expected reference `&[u8; 16]`
found reference `&[u8]`
I can see that foo[0..16]
is exactly 16 bytes, not a slice of unknown length [u8]
. How do I help the compiler see this?