Rust 抱怨在执行联合时没有为 HashSet 实现 BitOr,文档说明它应该是
Rust complains that BitOr isn't implemented for a HashSet when performing a union, docs state it should be
最小示例:
use std::collections::HashSet;
struct Something {
a: HashSet<Point>,
b: HashSet<Point>
}
impl Something {
fn TEST(&self) {
let new = self.a | self.b;
}
}
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
struct Point {
x: usize,
y: usize
}
检查一下 on the Rust Playground。如果你尝试编译这段代码,Rust 会报错 error[E0369]: no implementation for std::collections::HashSet<Point> | std::collections::HashSet<Point>
.
但是根据the docs对于HashSet,至少根据我的理解,应该为HashSet实现BitOr
特征,其中T: Eq + Hash + Clone
,Point
明明就在这里。那么到底发生了什么,我该如何解决?
仔细看看 implemention of BitOr
for HashSet
:
impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
where
...
BitOr
仅针对对 HashSet
的引用实现,不适用于拥有的值。
如下重写 Something::TEST
的实现将按预期进行编译。
impl Something {
fn TEST(&self) {
let new = &self.a | &self.b;
}
}
请注意,我们使用了对 self.a
和 self.b
的引用。
最小示例:
use std::collections::HashSet;
struct Something {
a: HashSet<Point>,
b: HashSet<Point>
}
impl Something {
fn TEST(&self) {
let new = self.a | self.b;
}
}
#[derive(Eq, PartialEq, Hash, Copy, Clone)]
struct Point {
x: usize,
y: usize
}
检查一下 on the Rust Playground。如果你尝试编译这段代码,Rust 会报错 error[E0369]: no implementation for std::collections::HashSet<Point> | std::collections::HashSet<Point>
.
但是根据the docs对于HashSet,至少根据我的理解,应该为HashSet实现BitOr
特征,其中T: Eq + Hash + Clone
,Point
明明就在这里。那么到底发生了什么,我该如何解决?
仔细看看 implemention of BitOr
for HashSet
:
impl<T, S> BitOr<&HashSet<T, S>> for &HashSet<T, S>
where
...
BitOr
仅针对对 HashSet
的引用实现,不适用于拥有的值。
如下重写 Something::TEST
的实现将按预期进行编译。
impl Something {
fn TEST(&self) {
let new = &self.a | &self.b;
}
}
请注意,我们使用了对 self.a
和 self.b
的引用。