2

I am getting a borrow of moved value error for this code:

playground

let mut foo = vec![1,2,3];
let bar = &mut foo;

for i in bar { // ...value moved here
    // whatever
}

bar.push(1); // borrow of moved value `bar`...

But how did the value of bar moved there? It's just a reference, right, so it should have been borrowed, not moved?

Nurbol Alpysbayev
  • 19,522
  • 3
  • 54
  • 89
  • 2
    I think this is the same problem as in [Retaking ownership of a mutable reference passed to a function accepting a generic type](https://stackoverflow.com/questions/48143889/retaking-ownership-of-a-mutable-reference-passed-to-a-function-accepting-a-gener). (The question is a little obscure but the answer is on point.) `for i in bar` calls `bar.into_iter()`, where `into_iter` is a trait function that takes `self`, so it doesn't trigger automatic reborrowing. You can solve it the same way, too. Does that answer your question? – trent Nov 25 '19 at 11:55
  • 2
    `for i in bar.iter_mut()` is probably what you are looking for – user2722968 Nov 25 '19 at 12:04
  • @trentcl Yes, exactly! Thank you! Why didn't you post answer? – Nurbol Alpysbayev Nov 25 '19 at 12:11
  • 2
    I prefer to link questions together, if possible, rather than write a new answer that is 90% the same as an existing answer. Marking this question as a duplicate may help future askers find the answer more easily, and if there are updates (let's say the auto-reborrowing algorithm changes so the original code becomes legal), the answer only needs to be updated in one place. – trent Nov 25 '19 at 12:21
  • 3
    Another solution is to explicitly reborrow the reference: `for i in &mut *bar` – Sven Marnach Nov 25 '19 at 15:15
  • @SvenMarnach Thank you, I think that may be useful in future as well. – Nurbol Alpysbayev Nov 25 '19 at 15:20

0 Answers0