find the sum of a list of numbers in rust

To find the sum of a list of numbers in Rust, you can use the iter() method to convert the array into an iterator and then use the fold() method to accumulate the sum of the elements. Here is an example:

main.rs
fn main() {
    let nums = vec![1, 2, 3, 4, 5];
    let sum: i32 = nums.iter().fold(0, |acc, x| acc + x);
    println!("Sum of the numbers is: {}", sum);
}
156 chars
6 lines

In this example, we first create a vector nums containing the numbers we want to sum. Then we call the iter() method on the vector to obtain an iterator over its elements. Finally, we call the fold() method on the iterator with two arguments: an initial value of 0 and a closure that takes two arguments, acc and x, representing the accumulated sum so far and the next element to be added, respectively. The closure returns the new accumulated sum after adding the current element. The result of fold() is the final sum, which we store in the variable sum and print to the console.

gistlibby LogSnag