1

I have something like this:

let test_data: [u8; 6] = [0, 1, 2, 3, 4, 5];

How can I get a &[u8; 3] pointing to the first three elements?

I know I can do test_data[0 .. 3], but that returns a slice [u8]. I'd also rather not convert the slice to an array if possible because I'm doing this with a ton of arrays and it needs to be as efficient as possible.

I'm doing this so that I can parse information from a byte array, so if there's an easier way to do that than splitting the array up, I'm also interested in that.

Shepmaster
  • 388,571
  • 95
  • 1,107
  • 1,366
meyer9
  • 1,120
  • 9
  • 26
  • 1
    `let piece: &[u8; 3] = test_data[0..3].try_into().unwrap()` – Shepmaster Sep 10 '19 at 19:26
  • 1
    My "challenge your assumptions" follow up would be: *why do you require an array reference (`&[u8; 3]`) instead of just accepting a slice (`&[u8]`)?* – Shepmaster Sep 10 '19 at 19:29
  • Well, I need a [u8; 8] for u64::from_be_bytes @Shepmaster. I guess the .try_into().unwrap() method is probably fast enough. – meyer9 Sep 10 '19 at 19:32
  • You may also want to look at [How can I convert a buffer of a slice of bytes (&\[u8\]) to an integer?](https://stackoverflow.com/q/29307474/155423). – Shepmaster Sep 10 '19 at 19:36
  • *probably fast enough* — yes, depending on exactly what you start with, that will be a free transformation (the panic from `unwrap` can even be removed in certain cases). – Shepmaster Sep 10 '19 at 19:37
  • 2
    thanks for the help! – meyer9 Sep 10 '19 at 19:40

0 Answers0