Collecting into a Vec
is so common that slices have a method to_vec
that does exactly this:
let b = a.to_vec();
You get the same thing as CodesInChaos's answer, but more concisely.
Notice that to_vec
requires T: Clone
. To get a Vec<T>
out of a &[T]
you have to be able to get an owned T
out of a non-owning &T
, which is what Clone
does.
Slices also implement ToOwned
, so you can use to_owned
instead of to_vec
if you want to be generic over different types of non-owning container. If your code only works with slices, prefer to_vec
instead.
The iterator only returns references to the elements (here &u8
). To get owned values (here u8
), you can used .cloned()
.
let a: &[u8] = &[0u8];
let b: Vec<u8> = a.iter().cloned().collect();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With