Consider the following rust code:
fn main() { let mut v = vec![1,2,3,4,5,6,7,8]; for elem in v.iter_mut() { *elem += 10; } println!("{:?}", v); } This code compiles and runs just as expected, adding 10 to each element of v. However according to my understanding of the borrowing and ownership rules, it seems to violate the rule disallowing aliased exclusive references (i.e. &mut references).
My understanding is that in the body of the loop, both elem and the &mut [i32] passed to [i32]::iter_mut to create the iterator are &mut references to the same memory, and therefore should not be allowed to coexists, but since the iterator is live for the entire loop statement, they are both live in the loop body. How can this be? What do I need to adjust about my understanding of the borrowing rules as they relate to exclusive references to reconcile this?
4 posts - 3 participants

