Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Filtering keys in hashmap in rust

I am not able to figure out why I am not getting keys filtered properly any hints

use std::collections::HashMap;

fn main() {
    let mut h: HashMap<&str, &str> = HashMap::new();
    h.insert("Hello", "World");
    h.insert("Aloha", "Wilkom");
    let dummy = h.keys().filter(|x| x.contains("Aloha"));
    println!("{:?}", dummy);
}

Output shows both the keys. I would expect only the key that matched

Filter { iter: ["Hello", "Aloha"] }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

This is an artifact of the Debug impl for filter’s return value. If you collect the keys into a Vec it works as expected:

use std::collections::HashMap;

fn main() {
    let mut h:HashMap<&str,&str> = HashMap::new();
    h.insert("Hello","World");
    h.insert("Aloha","Wilkom");
    let dummy: Vec<_> = h.keys().filter(|x| x.contains("Aloha")).collect();
    println!("{:?}",dummy);
}

(playground)

If you directly print out Filter, you get:

Filter { iter: ["Aloha", "Hello"] }

which technically is correct: dummy is a filter based on the iterator ["Aloha", "Hello"]

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading