How to operate on a chunk

Im trying to get an array of arrays from a chunk but I can't figure out how to do it.
everything I try gives an error

" a value of type Vec<u8> cannot be built from an iterator over elements of type &[u8]
the trait FromIterator<&[u8]> is not implemented for Vec<u8>rustcE0277", 19): required by a bound in collect"

I don't really know what this means or how to fix it... :frowning:

use std::error::Error;

fn main() -> Result<(), Box<dyn Error>> {

  let buf: [u8; 8] = [0x3A, 0xB9, 0xE5, 0xFF, 0x3A, 0xB9, 0xE5, 0xFF];
  let chunks = buf.chunks(4);

  // None of these work...
  let c = chunks.collect::<Vec<u8>>();
  let c = chunks.collect::<[u8]>();
  let c = chunks.collect::<&[u8]>();
  let c = chunks.collect::<&[u8; 4]>();


You will never be able to collect anything into a borrowed slice. It's a temporary view into a value that already existed, not something that can be by itself built from new data.

Semantics of Rust forbid code in collect from ever joining adjacent slices together back into the original, so you can't even rebuild &buf[..] back from its chunks.

The type you can collect to is Vec<&[u8]>, because you can create new Vecs, and the item type is a temporary view into your buf. But that's not a useful type.

You should probably do something like this:

for chunk in buf.chunks_mut(4) {
// edit chunk in place
1 Like

chunks returns (references to) slices, so if you need arrays, you'll have to do more.

I think what you really want is [T]::as_chunks, but that's not stable yet.

1 Like

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.