find the sum of all values in a map in rust

In Rust, you can find the sum of all the values in a HashMap by using the values method to get a reference to the collection of values, and then using the fold method to accumulate the sum.

Here is an example implementation:

main.rs
use std::collections::HashMap;

fn main() {
    let mut map = HashMap::new();
    map.insert("a", 1);
    map.insert("b", 2);
    map.insert("c", 3);

    let sum = map.values().fold(0, |acc, &x| acc + x);
    println!("Sum of values: {}", sum);
}
248 chars
12 lines

In this example, we create a HashMap with some integer values, and then use the values method to get a reference to the collection of values. We then use the fold method to start with an accumulator value of 0, and for each value in the collection, we add it to the accumulator. The result is the sum of all the values in the HashMap.

related categories

gistlibby LogSnag