Avatar ·

如何在 Rust 中为结构体的引用实现 Add trait?

你好!我正在学习 Rust,并尝试为我的结构体重载 `+` 运算符。我有一个结构体 `Point`,包含两个字段 `x` 和 `y`。我希望能够通过引用传递两个 `Point` 实例来相加,以避免移动所有权。 这是我的代码: ```rust struct Point { x: i32, y: i32, } impl std::ops::Add for Point { type Output = Point; fn add(self, other: Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } ``` 这可以工作,但它按值消耗了 `self` 和 `other`。我希望能够这样写: ```rust let a = Point { x: 1, y: 2 }; let b = Point { x: 3, y: 4 }; let c = &a + &b; ``` 我尝试这样写: ```rust impl std::ops::Add for &Point { type Output = Point; fn add(self, other: &Point) -> Point { Point { x: self.x + other.x, y: self.y + other.y } } } ``` 但编译器报错关于 lifetime。错误大致是:`mis