在 Rust 中过滤 hashmap 中的键

Gal*_*tus 2 rust

我无法弄清楚为什么我没有正确过滤任何提示的密钥

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);
}
Run Code Online (Sandbox Code Playgroud)

输出显示两个键。我期望只有匹配的密钥

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);
}
Run Code Online (Sandbox Code Playgroud)

lko*_*bly 7

Debug这是过滤器返回值的实现的产物。如果您将密钥收集到 a 中,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);
}
Run Code Online (Sandbox Code Playgroud)

游乐场

如果直接打印出来Filter,你会得到:

Filter { iter: ["Aloha", "Hello"] }
Run Code Online (Sandbox Code Playgroud)

从技术上讲,这是正确的:dummy是基于迭代器的过滤器["Aloha", "Hello"]