find the sum of all keys in a map in rust

To find the sum of all keys in a Rust HashMap, you can iterate over each key-value pair in the map and add the key to a running total. Here's an example implementation:

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

fn sum_keys(map: &HashMap<i32, i32>) -> i32 {
    let mut sum = 0;
    for key in map.keys() {
        sum += key;
    }
    sum
}
163 chars
10 lines

In this function, we define a sum variable to keep track of the running total. We then iterate over the keys of the input HashMap, adding each key to the sum variable. Finally, we return the computed sum.

You can call this function with your HashMap as an argument to get the sum of all keys:

main.rs
let mut map = HashMap::new();
map.insert(1, 10);
map.insert(2, 20);
map.insert(3, 30);

let sum = sum_keys(&map);
println!("Sum of keys: {}", sum);
148 chars
8 lines

This will output:

main.rs
Sum of keys: 6
15 chars
2 lines

related categories

gistlibby LogSnag