m.r*_*nal 16 union hashset rust
我有两个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
Run Code Online (Sandbox Code Playgroud)
错误消息如下:
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
Run Code Online (Sandbox Code Playgroud)
我该如何表演a = a U b?
hel*_*low 22
你不想要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}
}
Run Code Online (Sandbox Code Playgroud)
(游乐场)
Extend::extend也为其他集合实现,例如Vec. for 的结果Vec会有所不同,因为Vec它不像 aSet那样尊重重复项。