I'm attempting to simply convert a slice to a vector. The following code:
let a = &[0u8];
let b: Vec<u8> = a.iter().collect();
fails with the following error message:
3 | let b: Vec<u8> = a.iter().collect();
| ^^^^^^^ a collection of type `std::vec::Vec<u8>` cannot be built from an iterator over elements of type `&u8`
What am I missing?
Collecting into a
Vec
is so common that slices have a methodto_vec
that does exactly this:You get the same thing as CodesInChaos's answer, but more concisely.
Notice that
to_vec
requiresT: Clone
. To get aVec<T>
out of a&[T]
you have to be able to get an ownedT
out of a non-owning&T
, which is whatClone
does.Slices also implement
ToOwned
, so you can useto_owned
instead ofto_vec
if you want to be generic over different types of non-owning container. If your code only works with slices, preferto_vec
instead.The iterator only returns references to the elements (here
&u8
). To get owned values (hereu8
), you can used.cloned()
.