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