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)