Reputation: 4874
As of now, I am using hardcoded code to replace the vector. What is the most effective way to achieve this?
fn main() {
let mut v = vec![1, 2, 3, 4, 5, 6, 7, 8, 9];
let u = vec![0,0,0,0];
v[2] = u[0];
v[3] = u[1];
v[4] = u[2];
v[5] = u[3];
println!("v = {:?}", v);
}
Is there any function to replace the vector with given indices?
Upvotes: 0
Views: 327
Reputation: 737
Another way:
let offset : usize = 2;
u.iter().enumerate().for_each(|(index, &val)| {
v[index + offset] = val;
});
Upvotes: 1
Reputation: 71450
For Copy
types:
v[2..][..u.len()].copy_from_slice(&u);
For non-Copy
types:
v.splice(2..2 + u.len(), u);
Upvotes: 5