Follow up this question which is marked as duplicate as question here.
The concept of how for loop implement into_iter
keeps haunt me down and this answer kinda creates more question to me like the terms of re-borrow, which is not mentioned in rust official document at all except in one place.
To my understanding of this comment, when vec is a mutable reference, for i in vec.into_iter()
is actually for i in (&mut *vec).into_iter()
behind the scene.
How about for i in vec
, is it actually i in vec.into_iter()
? Is there any place that have more detail on how for loop is implemented and how re-borrowing gets triggered and how it works?
Code for reference:
fn question1_1(vec: &mut [i32]) {
for &mut item in vec.into_iter() {
println!("{}", item);
}
for &mut item in vec { // --- `vec` moved due to this implicit call to `.into_iter()`
println!("{}", item);
}
vec; // Error: move occurs because `vec` has type `&mut [i32]`, which does not implement the `Copy` trait
}
pub fn main() {
let mut s = vec![1, 2, 3];
question1_1(&mut s);