我有两个 HashSet<u16>
s,我想实现 a = a U b
.如果可能的话,我想使用 HashSet::union
而不是循环或其他调整。
我尝试了以下方法:
use std::collections::HashSet;
let mut a: HashSet<u16> = [1, 2, 3].iter().cloned().collect();
let b: HashSet<u16> = [7, 8, 9].iter().cloned().collect();
// I can build a union object that contains &u16
let union: HashSet<&u16> = a.union(&b).collect();
// But I can't store the union into a
a = a.union(&b).collect(); // -> compile error
// of course I can do
for x in &b {
a.insert(*x);
}
// but I wonder if union could not be used to simply build a union
错误信息如下:
the trait bound
`std::collections::HashSet<u16>: std::iter::FromIterator<&u16>`
is not satisfied
我如何执行 a = a U b
?
最佳答案
您不需要 union
— 如您所说,它将创建一个新的 HashSet
。相反,您可以使用 Extend::extend
:
use std::collections::HashSet;
fn main() {
let mut a: HashSet<u16> = [1, 2, 3].iter().copied().collect();
let b: HashSet<u16> = [1, 3, 7, 8, 9].iter().copied().collect();
a.extend(&b);
println!("{:?}", a); // {8, 3, 2, 1, 7, 9}
}
( Playground )
Extend::extend
也是 implemented for other collections ,例如向量
。 Vec
的结果会有所不同,因为 Vec
不像 Set
那样接受重复项。
关于rust - 如何将一个 HashSet 的所有值插入另一个 HashSet?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56148586/