find the smallest key in a map in rust

To find the smallest key in a HashMap in Rust, you can use the keys() function to get an iterator over the keys and then use the min() method to find the minimum key.

Here's a code snippet that shows how to do this:

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

fn main() {
    let mut map = HashMap::new();
    map.insert(3, "c");
    map.insert(1, "a");
    map.insert(2, "b");
    
    if let Some(min_key) = map.keys().min() {
        println!("The smallest key is {}", min_key);
    }
}
262 chars
13 lines

In this example, the HashMap contains three key-value pairs with keys 3, 1, and 2. We use the keys() method to get an iterator over the keys, and then call the min() method on the iterator to find the smallest key.

The min() method returns an Option<&K> where K is the type of the keys in the HashMap. Since the result might be None if the HashMap is empty, we use a if let statement to extract the minimum key from the Option. If the Option is Some, we print out the smallest key.

related categories

gistlibby LogSnag