I m new to rust and going through the Google course for exercises as I go through "the book", I m on one of the exercises and I am needing to implement the +
operator. So I go to the docs and see this page on it and immediately wonder about the lack of ampersands in the args to add
for the example, quoted below, permalink to playground
pub struct Point {
x: f64,
y: f64,
}
impl std::ops::Add<Point> for Point {
type Output = Point;
fn add(&self, b: &Point) -> Point {
Self {
x: self.x + b.x,
y: self.y + b.y,
}
}
}
Why would I not expect that the arguments to add
are immutable references instead of borrows moves? And it s not just the docs, the compiler wants it too,
Compiling playground v0.0.1 (/playground)
error[E0053]: method `add` has an incompatible type for trait
--> src/lib.rs:8:12
|
8 | fn add(&self, b: &Point) -> Point {
| ^^^^^
| |
| expected `Point`, found `&Point`
| help: change the self-receiver type to match the trait: `self`
|
= note: expected signature `fn(Point, Point) -> Point`
found signature `fn(&Point, &Point) -> Point`
For more information about this error, try `rustc --explain E0053`.
error: could not compile `playground` (lib) due to previous error
Why might the creators of Rust enforce that addition (per it s usual definitions) design it this way? I imagine this works well for literals, but I believe that references would work for literals as well too. What am I missing?