我不明白为什么我没有正确过滤密钥任何提示
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);
}
输出显示两个键。我希望只有匹配的密钥
Filter { iter: ["Hello", "Aloha"] }
这是过滤器返回值的Debug
impl的工件。如果您将密钥收集到Vec
中,它将按预期工作:
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);
}
(操场(
如果你直接打印出Filter
,你会得到:
Filter { iter: ["Aloha", "Hello"] }
这在技术上是正确的:dummy
是一个基于迭代器["Aloha", "Hello"]
的过滤器