如何将一个 HashSet 的所有值插入到另一个 HashSet 中?

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那样尊重重复项。

  • 太好了,正是我要找的。此外,它教会我不仅应该查看文档的“方法”部分来查找方法,还应该查看结构实现的特征。Rust 本身就是一个世界:-) (2认同)