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