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"] }
>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);
}
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"]