Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

For Copy types:

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

Playground.

For non-Copy types:

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

Playground.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading