Rust的HashSet::intersection函数创建了一个新的HashSet。如何通过两个HashSet交集的结果来更新原始HashSets?
fn main() {
// intersecting two HashSets, creating a new HashSet: OK
use std::collections::HashSet;
let a = HashSet::from(["first", "second", "third"]);
let b = HashSet::from(["first", "third", "fifth", "ninth"]);
let intersection: HashSet<_> = a.intersection(&b).collect();
println!("{:?}", intersection);
// intersecting two HashSets, updating the original HashSet: Failed
let mut a = HashSet::from(["first", "second", "third"]);
let b = HashSet::from(["first", "third", "fifth", "ninth"]);
println!("{:?}", a.intersection(&b).collect::<HashSet<_>>());
println!("{:?}", a);
a = a.intersection(&b).collect::<HashSet<_>>(); // doesn't work
// filter: verbose
let mut a = HashSet::from(["first", "second", "third"]);
let b = HashSet::from(["first", "third", "fifth", "ninth"]);
a = a.iter().filter(|&s| b.contains(s)).map(|s| *s).collect::<HashSet<_>>();
println!("{:?}", a);
}发布于 2022-06-12 07:04:40
要做到这一点而不分配新的HashSet,您可以使用HashSet::retain,并且只保留第二个HashSet中存在的元素。
fn main() {
use std::collections::HashSet;
let mut a = HashSet::from(["first", "second", "third"]);
let b = HashSet::from(["first", "third", "fifth", "ninth"]);
println!("{:?}", a.intersection(&b).collect::<HashSet<_>>());
a.retain(|x| b.contains(x));
println!("{:?}", a);
}输出:
{"third", "first"}
{"first", "third"}https://stackoverflow.com/questions/72590088
复制相似问题