Skip to content

Instantly share code, notes, and snippets.

@spikespaz
Forked from danielhenrymantilla/vec_of_array.md
Created January 9, 2022 13:18
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save spikespaz/47ae7161625525a764680f811bf5b35a to your computer and use it in GitHub Desktop.
Save spikespaz/47ae7161625525a764680f811bf5b35a to your computer and use it in GitHub Desktop.
Vec off arrays (or slices)

The most technically-correct answer to that question: make a Vec of references:

array.iter_mut().collect::<Vec<_>>();

no cloning involved, and you have a Vec.

In practice, however, it's gonna be lifetime-bound (Vec<&mut T> or Vec<&T> if using .iter()). Hence the following more useful answer, but it may involve cloning or other stuff:

To avoid extra lifetime/borrowing restrictions, you'll need to have owned values in the resulting Vec. For that, you:

  • either go from T -> T, by moving, e.g.,

    ::std::array::IntoIter::new(array) // does not work for slices because of lack of `&own` references.
        .collect::<Vec<_>>()
  • or &T -> T, by cloning, e.g.,

    array.iter() // works for slices
        .cloned()
        .collect::<Vec<_>>()
  • or &mut T -> T, by taking / replacing, e.g.,

    array.iter_mut() // works for slices
        .map(|it| mem::take(it)) // or .map(|it| mem::replace(it, somme_dummy))
        .collect::<Vec<_>>()

You can support moving with slices if it was behind a Box:

let _: Box<[T]> = boxed_slice;
Vec::from(boxed_slice)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment