Move value from an iterator

I'm trying to move a value from an iterator, created from a vector:


#[derive(Debug)]
enum E {
    A,
    B(String)
}

fn f(mut items : Iter<E>) -> String {
    match items.next() {
        Option::None => "nothing".to_string(),
        Option::Some(e) => match e {
            E::A => "A".to_string(),
            E::B(s) => s
        },
    }
}

fn main() {
    let mut t = vec![E::B("string".to_string())];
    let v = f(t.iter());
}

But this doesn't work since t.iter() created an iterator over the references of elements of t. How do I create an iterator from which values can be moved out of the vector? The creation of iterator should consume the ownership of original vector.

The into_iter() method does what you want. It consumes the vector and iterates over the values in the vector. It is in its own trait since it is used as part of for loop semantics. So you can write:

let v = f(t.into_iter());

In case you want to move items while keeping the container's memory allocation for further use, there is the drain(..) iterator.

2 Likes

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.