Swaroop Maddu
Swaroop Maddu

Reputation: 4874

How to replace portion of a vector using Rust?

What is the best way to replace a specific portion of a vector with a new vector?

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);
}

Permalink to the playground

Is there any function to replace the vector with given indices?

Upvotes: 0

Views: 327

Answers (2)

GRASBOCK
GRASBOCK

Reputation: 737

Another way:

let offset : usize = 2;
u.iter().enumerate().for_each(|(index, &val)| {
   v[index + offset] = val;
});

Playground

Upvotes: 1

Chayim Friedman
Chayim Friedman

Reputation: 71450

For Copy types:

v[2..][..u.len()].copy_from_slice(&u);

Playground.

For non-Copy types:

v.splice(2..2 + u.len(), u);

Playground.

Upvotes: 5

Related Questions