Cómo implementar el trait Add para una referencia a una estructura en Rust
¡Hola! Estoy aprendiendo Rust y tratando de sobrecargar el operador `+` para mi estructura. Tengo una estructura `Point` con dos campos `x` e `y`. Quiero poder sumar dos instancias de `Point` pasándolas por referencia para no mover la propiedad.
Aquí está mi código:
```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 }
}
}
```
Esto funciona, pero consume `self` y `other` por valor. Quiero poder escribir:
```rust
let a = Point { x: 1, y: 2 };
let b = Point { x: 3, y: 4 };
let c = &a + &b;
```
Intenté escribir esto:
```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 }
}
}
```
Pero el compilador se queja sobre el tiempo de vida (lifetime). El error es algo como: `mis
No answers yet.
Inicia sesión para dejar una respuesta
Blogs