How to implement the Add trait for a reference to a struct in Rust?
Hello! I'm learning Rust and trying to overload the `+` operator for my struct. I have a `Point` struct with two fields `x` and `y`. I want to be able to add two `Point` instances by passing them by reference, so as not to move ownership.
Here's my code:
```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 }
}
}
```
This works, but it consumes `self` and `other` by value. I want to be able to write:
```rust
let a = Point { x: 1, y: 2 };
let b = Point { x: 3, y: 4 };
let c = &a + &b;
```
I tried writing this:
```rust
impl std::ops::Add for &Point {
type Output = Point;
No answers yet.
Log in to leave an answer