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

Rust consume a vector inside a struct

I have a Container struct containing a vector, which I’d like to consume while doing some work on it. For a standalone vector the following works:

fn empty(vec : &mut Vec<f32>){
    vec.into_iter().for_each(|x|println!("value: {:?}", x));
}

fn main() {
    let mut vec = vec![1.0,2.0,3.0,4.0];
    empty(&mut vec);
    assert!(0 == vec.len());
}

However, trying this with the Container structure introduce fails:

struct Container{
    vec : Vec<f32>,
}

fn empty(c : &mut Container){
    c.vec.into_iter().for_each(|x|println!("value: {:?}", x));
}

fn main() {
    let mut container = Container{
        vec: vec![1.0,2.0,3.0,4.0]
    };
    empty(&mut container);
}

One Solution I think would work is to iterate over the vector without consuming it, and then assign an empty vector.

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

fn empty(c : &mut Container){
    c.vec.iter().for_each(|x|println!("value: {:?}", x));
    c.vec = Vec::new();
}

But is there a better way to do it?

>Solution :

You can use Vec::drain to remove elements from your vector and create an iterator from the removed elements:

struct Container{
    vec : Vec<f32>,
}

fn empty(c : &mut Container){
    c.vec.drain(..).for_each(|x|println!("value: {:?}", x));
}

fn main() {
    let mut container = Container{
        vec: vec![1.0,2.0,3.0,4.0]
    };
    empty(&mut container);
    assert!(container.vec.is_empty());
}

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