I'm averaging a vector of i32
numbers:
let v = vec![100, 32, 57, 1, 4, 6, 7];
let mut avg: f32 = 0.0;
for num in v {
avg += num as f32;
}
avg /= v.len() as f32;
println!("Average is {}", avg)
I get an error:
error[E0382]: borrow of moved value: `v`
--> src/main.rs:8:12
|
2 | let v = vec![100, 32, 57, 1, 4, 6, 7];
| - move occurs because `v` has type `std::vec::Vec<i32>`, which does not implement the `Copy` trait
...
5 | for num in v {
| -
| |
| value moved here
| help: consider borrowing to avoid moving into the for loop: `&v`
...
8 | avg /= v.len() as f32;
| ^ value borrowed here after move
I know that v is moved due to the IntoIterator::into_iter
call according to this answer, but I don't get it why the iterator takes the ownership ?
Would any one elaborate more on the moving aspect here in the for loop?