0

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?

Shady Atef
  • 2,121
  • 1
  • 22
  • 40
  • 1
    I guess it moved *because* you did not use a reference. The loop will own the vector rather than borrowing it – Marv Apr 14 '20 at 15:29
  • @Frxstrem, Yes it does partially, but my question is why the for loop takes the ownership ? – Shady Atef Apr 14 '20 at 15:33
  • 1
    That's the default behavior. The syntax will automatically convert the value into an iterator (via `IntoIterator::into_iter`), which consumes that value. – E_net4 Apr 14 '20 at 15:36

0 Answers0