HiveBrain v1.2.0
Get Started
← Back to all entries
patternrustCritical

What's the idiomatic way to append a slice to a vector?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
idiomaticslicetheappendvectorwaywhat

Problem

I have a slice of &[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 slice


Is 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: Vec::extend_from_slice

Example:

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.