find the smallest value in a map in rust

To find the smallest value in a map in Rust, you can iterate over the key-value pairs in the map and use the min_by_key method to find the minimum value.

Here's an example:

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

fn main() {
    let mut map = HashMap::new();
    map.insert("A", 10);
    map.insert("B", 5);
    map.insert("C", 15);

    let smallest_value = map.iter()
        .min_by_key(|&(_, v)| v)
        .unwrap()
        .1;

    println!("The smallest value in the map is {}", smallest_value);
}
324 chars
16 lines

In this example, we create a new HashMap and insert some key-value pairs. We then use the iter method to iterate over the key-value pairs in the map. We pass a closure to the min_by_key method that extracts the value from each key-value pair, and returns the minimum value.

The result of min_by_key is an Option that may be empty if the map is empty. We unwrap the Option to get the smallest value, and print it to the console.

If you run this code, you should see the following output:

main.rs
The smallest value in the map is 5
35 chars
2 lines

related categories

gistlibby LogSnag