0

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?

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
fadedbee
  • 42,671
  • 44
  • 178
  • 308
  • For this particular case I would just do: `let mut bar = [0; 16]; bar.copy_from_slice(&foo[0..16]);`. – rodrigo Jun 30 '20 at 19:49

1 Answers1

2

Your problem isn't that you can't reference a slice of bytes; it's that a slice is not an array.

Probably you want the arrayref crate or the TryInto trait. There's also some discussion on doing this automatically in this Github issue.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
Putnam
  • 704
  • 4
  • 14