This Rust tutorial explains the fold()
mechanism well, and this example code:
let sum = (1..4).fold(0, |sum, x| sum + x);
works as expected.
I'd like to run it on a vector, so based on that example, first I wrote this:
let sum: u32 = vec![1,2,3,4,5,6].iter().fold(0, |sum, val| sum += val);
which threw an error:
error: binary assignment operation `+=` cannot be applied to types `_` and `&u32` [E0368]
let sum = ratings.values().fold(0, |sum, val| sum += val);
^~~~~~~~~~
I guessed this might be a reference-related error for some reason, so I changed that to fold(0, |sum, &val| sum += val)
, which resulted in
error: mismatched types:
expected `u32`,
found `()`
Hm, maybe something's wrong with the closure? Using {sum += x; sum }
, I got
binary assignment operation `+=` cannot be applied to types `_` and `&u32`
again.
After further trial and error, adding mut
to sum
worked:
let sum = vec![1,2,3,4,5,6].iter().fold(0, |mut sum, &x| {sum += x; sum});
Could someone explain the reason why fold()
for vectors differs so much from the tutorial? Or is there a better way to handle this?
For reference, I'm using Rust beta, 2015-04-02.