Why doesn't a for loop require a mutable iterator?

If I want to use the iterator manually, it must be changed:

let test = vec![1,2,3]; let mut test_mut = test.iter(); while let Some(val) = test_mut.next() { println!("{:?}",val); } 

But I can use it with a for loop with pleasure, even if it is immutable.

 let test_imm = test.iter(); for val in test_imm { println!("{:?}",val); } 

I think this roughly works because test_imm is moved to the for loop block, so test_imm can no longer be used by the outer block and (from the point of view of the outer block) is unchanged until the for loop, and then it is unavailable, so everything is fine.

It is right? Is there any other explanation?

Ed: Yeah, this is more or less explained here .

+5
source share
1 answer

That's for sure. Since it has moved to the for loop, the for loop now owns it and can do whatever it wants with it, including "make it" mutable. Consider this similar example, where we seem to mutate xs , although it is immutable, but in fact it is because we move it, so the new owner has the right to do whatever he wants with it, including re-linking it as volatile

 let xs: Vec<i32> = vec![1, 2, 3]; fn append(v: Vec<i32>, x: i32) -> Vec<i32> { let mut my_v = v; my_v.push(x); my_v } let appended = append(xs, 4); 

playpen

Note that this function can be abbreviated using the syntax of the convenient mut parameter:

 fn append(mut v: Vec<i32>, x: i32) -> Vec<i32> { v.push(x); v } 
+7
source

All Articles