If I try to iterate over a slice twice, it works fine:
let a = &[1, 2, 3];
for i in a {
println!("{}", i);
}
for i in a { // works fine
println!("{}", i);
}
If I try to iterate over a vector twice, it fails:
let a = vec![1, 2, 3];
for i in a {
println!("{}", i);
}
for i in a {
println!("{}", i);
}
error[E0382]: use of moved value: `a`
--> src/main.rs:6:14
|
3 | for i in a {
| - value moved here
...
6 | for i in a {
| ^ value used here after move
|
= note: move occurs because `a` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
I see that the IntoIterator
trait takes self
by value, so it makes sense to me that the second example fails. Why does the first example succeed?
a
isn't actually a slice, it's a reference to an array of length 3. However, deref coercions allow a reference to an array to act like a slice in most cases.a
in the first example is&[i32; 3]
, while a slice would be&[i32]
? Also, is the deref coercion you mentioned visible in the list here, or is it more magical?