"方法"sub"具有不兼容的trait类型"(sub可以为不同的结构实现吗?)



我正在尝试编写两个结构PointBound,以便您可以从Bound中减去Point

代码:

struct Point {
x:usize,
y:usize,
}
impl Sub for Point {
type Output = Point;
fn sub(self,other:Point) -> Point {
Point { x:self.x-other.x, y:self.y-other.y }
}
}
struct Bound { min:Point,max:Point }
impl Sub for Bound {
type Output = Bound;
fn sub(self,other:Point) -> Bound {
Bound { min:self.min-other, max:self.max-other }
}
}

我得到错误:

method `sub` has an incompatible type for trait
expected struct `construct::Bound`, found struct `construct::Point`
note: expected fn pointer `fn(construct::Bound, construct::Bound) -> construct::Bound`
found fn pointer `fn(construct::Bound, construct::Point) -> construct::Bound`rustc(E0053)
main.rs(565, 9): expected struct `construct::Bound`, found struct `construct::Point`

我在这里尝试的方式可能吗?最好的方法是什么?

Sub有一个参数Rhs,默认为Self。CCD_ 8是CCD_。您可能希望添加impl Sub<Point> for Bound

impl Sub<Point> for Bound {
type Output = Bound;
fn sub(self, other: Point) -> Bound {
Bound { min:self.min - other, max:self.max - other }
}
}

注意:这并不完全有效,因为当前的impl Sub for Point实际上与第一个-一起消耗了other,而为第二个-留下了"移动值的使用"。最简单的事情可能是在Point上只使用#[derive(Clone, Copy)]

最新更新