find the keys of a map in rust

To find the keys of a HashMap in Rust, you can iterate through the keys using a loop or iterator. Here's an example of how to do it with a loop:

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

fn main() {
    let mut map = HashMap::new();
    map.insert("key1", "value1");
    map.insert("key2", "value2");
    map.insert("key3", "value3");

    // loop through the keys and print them
    for key in map.keys() {
        println!("{}", key);
    }
}
290 chars
14 lines

In this example, we create a HashMap and insert some key-value pairs. We then loop through the keys using map.keys(), which returns an iterator over the keys. We print each key using println!() inside the loop.

Alternatively, you can use the iter() method to iterate over key-value pairs, and then extract only the keys:

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

fn main() {
    let mut map = HashMap::new();
    map.insert("key1", "value1");
    map.insert("key2", "value2");
    map.insert("key3", "value3");

    // loop through the key-value pairs and extract the keys
    for (key, _) in map.iter() {
        println!("{}", key);
    }
}
312 chars
14 lines

In this example, we use map.iter() to get an iterator over key-value pairs. In the loop, we destructure each pair into its key and value parts, but only use the key with println!().

gistlibby LogSnag