Rust 中的复合 `HashSet` 操作或如何在 Rust 中获得 `HashSet` 的显式差异/并集

mae*_*rin 3 hashset rust

我想用伪代码执行以下操作:

(a, b, c) = (HashSet(...), HashSet(...), HashSet(...))

(a, b, c) = (a - b - c, b - a - c, c - a - b)
Run Code Online (Sandbox Code Playgroud)

在 Rust 中我尝试了这样的事情:

(a, b, c) = (HashSet(...), HashSet(...), HashSet(...))

(a, b, c) = (a - b - c, b - a - c, c - a - b)
Run Code Online (Sandbox Code Playgroud)

现在我们要从这些HashSets 中排除所有常见的“单词”。我了解到difference方法union返回DifferenceUnion迭代器。如果我这样做:

fn get_random_set(...) -> HashSet<String> {
    ...
}

// Sets of randomly generated "words" that define behavior of the whole program.
let action_plus: HashSet<String> = get_random_set();
let action_minus: HashSet<String> = get_random_set();
let action_new_line: HashSet<String> = get_random_set();
Run Code Online (Sandbox Code Playgroud)

我收到这个:

the trait `From<Vec<String>>` is not implemented for `HashSet<_, _>`
Run Code Online (Sandbox Code Playgroud)

如何处理这个问题呢?

Ale*_*uze 5

直接收集到HashSet 中HashSet,而不是Vec使用impl FromIterator 。

那是:

let action_plus: HashSet<_> = action_minus.union(&action_new_line).collect();
Run Code Online (Sandbox Code Playgroud)

正如 Chayim 在评论中所说,您也可以使用|( BitOr) 运算符,因为HashSet 实现了它并且正如文档所说:

返回 self 和 rhs 的并集作为新的 HashSet<T, S>

如果您查看它的实现,您会发现它的功能与上面的代码基本相同(尽管它从这些集合中克隆了项目):

impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
where
    T: Eq + Hash + Clone,
    S: BuildHasher + Default,
{
    type Output = HashSet<T, S>;

    fn bitor(self, rhs: &HashSet<T, S>) -> HashSet<T, S> {
        self.union(rhs).cloned().collect()
    }
}
Run Code Online (Sandbox Code Playgroud)

HasSet还实现了用于创建交集的BitAnd ( &) 运算符、用于创建集合差值的Sub ( ) 和用于创建对称差值的BitXor ( ) 运算符。-^

您可以使用这些便利运算符,但是当人们没有想到它们时,它们可能会令人反感,因此请小心使用它们。

  • 或者,更短,`&amp;action_minus | &amp;action_new_line`。 (3认同)