To my understanding, for loop implicitly call into_iter()
on vector to loop through it.
However, in the code below, why does vec
in the first for loop in question1_1 not consumed, but vec in the second for loop does?
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);
No matter the variable in loop is &mut item
or item
, it's all showing the same error
fn question1_2(vec: &mut [i32]){
for item in vec.into_iter() {
println!("{} {:p}", item, item);
}
for item in vec { // -- vec` moved due to this implicit call to `.into_iter()`
println!("{} {:p}", item, 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_2(&mut s);