gpt4 book ai didi

rust - `method ` sub ` has an incompatible type for trait`(可以为不同的结构实现sub吗?)

转载 作者:行者123 更新时间:2023-12-03 11:43:14 30 4
gpt4 key购买 nike

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

代码:

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,默认为Selfimpl Sub for Boundimpl Sub<Bound> for Bound的缩写。您可能要添加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消耗了 -,而第二个 -保留了“使用移动值”。最简单的方法可能只是将 #[derive(Clone, Copy)]放在 Point上。

关于rust - `method ` sub ` has an incompatible type for trait`(可以为不同的结构实现sub吗?),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61536009/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com