Sum or Product of an Array in Rust

I’ve been learning Rust (or “rustlang” for Google purposes – don’t even bother searching for “Rust on Windows”)  and it has been more difficult than anticipated because of the shifting foundation of the language.  Much of what you find online is out-of-date and the documentation is not terribly helpful unless you know what you are looking for already.

Which brings me to the seemingly simple task of taking the sum or product of an array of numbers.  After writing a silly iteration loop for the thousandth time, I decided to find an easier way.  Fortunately, a couple of Google searches led me here, which referenced a fold method on the iterator.

The method takes 2 arguments – an initial value, and a 2 parameter function, where the first parameter is the result of the last call to the function (or the initial value) and the second parameter is the current element of the array.

Using this, you can condense the following:


let mut sum = 0u; 
for i in range(0u,numbers.len()) { 
  sum += numbers[i]; 
} 

To this:


let sum = numbers.iter().fold(0,|a, &b| a + b); 

Not only is that less code, but we no longer need to make the sum mutable!  On the first loop through, this will assign the initial value (0) to a, and the first number in the array to &b (we are “borrowing” the value – hence the &).  The expression is then calculated and the result returned.  If there are more elements, we assign the result to a and the next element to &b until there are no elements left.

Very nifty – and definitely a method that will go in the toolbag.  Now if only rust-lang was more discoverable.  Perhaps when the API becomes more stable.