patternrustCritical
What's the idiomatic way to append a slice to a vector?
Viewed 0 times
idiomaticslicetheappendvectorwaywhat
Problem
I have a slice of
Is there a better way to do this in Rust stable? (
&[u8] and I'd like to append it to a Vec with minimal copying. Here are two approaches that I know work:let s = [0u8, 1u8, 2u8];
let mut v = Vec::new();
v.extend(s.iter().map(|&i| i));
v.extend(s.to_vec().into_iter()); // allocates an extra copy of the sliceIs there a better way to do this in Rust stable? (
rustc 1.0.0-beta.2)Solution
There's a method that does exactly this:
Example:
Vec::extend_from_sliceExample:
let s = [0u8, 1, 2];
let mut v = Vec::new();
v.extend_from_slice(&s);Code Snippets
let s = [0u8, 1, 2];
let mut v = Vec::new();
v.extend_from_slice(&s);Context
Stack Overflow Q#29998515, score: 154
Revisions (0)
No revisions yet.