snippetrustModerate
How to convert from &[u8] to Vec<u8>?
Viewed 0 times
convertvechowfrom
Problem
I'm attempting to simply convert a slice to a vector. The following code:
fails with the following error message:
What am I missing?
let a = &[0u8];
let b: Vec = a.iter().collect();fails with the following error message:
3 | let b: Vec = a.iter().collect();
| ^^^^^^^ a collection of type `std::vec::Vec` cannot be built from an iterator over elements of type `&u8`What am I missing?
Solution
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 = a.iter().cloned().collect();Code Snippets
let a: &[u8] = &[0u8];
let b: Vec<u8> = a.iter().cloned().collect();Context
Stack Overflow Q#47980023, score: 20
Revisions (0)
No revisions yet.