How to consume value in iter_mut().map()?

What I want is to accept a vector of Type's by taking ownership to it, then process every Type and make a reference counter from it, which will then be stored in the struct. Here is the code.

    fn foo(&mut self, input : Vec<Type>) {
        input.iter_mut().map(|x| self.data.push(Rc::new(*x)));
    }

The compiler says that I cannot move the value of x, which is behind a mutable reference. Well, that is clear, we cannot move something which is borrowed in any case, but how do I tell the compiler that I actually want to consume the values and move them into these Rc::new() constructions? I think logically it may be possible, as the method signature says that the input will be owned by this function.

use into_iter instead of iter_mut.
iter_mut allows you to modify values in-place, while into_iter actually consumes them.

This is exactly what I wanted and it works, thank you.

It isn't actually your question and I'm not sure if it happened because you tried to shrink the example, but your code won't actually add anything from input to self.data.
This is because iterators in rust are "lazy" as in not every method on the iterator (here map) consumes the iterator.
A small example how it doesn't work
There are a number of methods that consume an iterator, in this case you could use for_each instead of map.

1 Like

I have just tried, and you are right, thank you for bringing this up.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.