I’m new to this language and am currently reading Rust in action. I understand why you’re able to access the vector after a for loop. However, I don’t understand why this works:
let list = [1, 2, 3, 4, 5];
for item in list {
println!("{}", item);
}
println!("{:#?}", list);
If I try the same with a vector, it doesn’t work without it being a reference inside the for, which I understand why.
>Solution :
Arrays of numbers are never moved. Arrays are Copy if their underlying type is Copy, which means that, like basic numerical types, they’re always copied rather than moved. They’re eligible for this special treatment since an array is just a contiguous chunk of the bytes representing its elements, so if its elements can be copied byte-by-byte, then so can the whole array. A vector, on the other hand, involves dynamic allocation and pointers, so blindly copying the bytes of a vector isn’t safe.
When you use a for loop, you’re invoking into_iter on the type, which takes self by value. For a type that’s not Copy, this requires the target of the for loop to be moved to construct the iterator. But for types that are Copy, Rust makes a copy of the array and then uses that copy in into_iter instead.
As the relevant documentation (linked above) says:
[…] Creates a consuming iterator, that is, one that moves each value out
of the array (from start to end). The array cannot be used after
calling this unless T implementsCopy, so the whole array is copied.
emphasis mine