This doesn't work:
let vectors = vec![1, 2, 3, 4, 5, 6, 7];
for i in vectors {
println!("Element is {}", i);
}
let largest = vectors[0];
Error message:
error[E0382]: borrow of moved value: `vectors`
--> src/main.rs:8:19
|
2 | let vectors = vec![1, 2, 3, 4, 5, 6, 7];
| ------- move occurs because `vectors` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
3 |
4 | for i in vectors {
| -------
| |
| value moved here
| help: consider borrowing to avoid moving into the for loop: `&vectors`
...
8 | let largest = vectors[0];
| ^^^^^^^ value borrowed here after move
The vector has been moved into the loop. Its ownership — and that of its individual elements — has been transferred there permanently.
But this works:
let largest = vectors[0];
let largest2 = vectors[0];
I don't know why; the vectors[0]
value should have been moved to largest
and largest2
should then fail, but it didn't.