Consider the following struct representing a Point:
struct Point { x:i32, y:i32, }
I tried to overload the plus operator for this struct like this:
impl ops::Add<Point> for Point {
type Output = Point;
fn add(self, rhs:Point) -> Self::Output {
Point{x:(self.x + rhs.x), y:(self.y + rhs.y)}
}
}
then I tested it and it worked as expected:
let mut p1:Point = Point{x:1, y:1};
let mut p2:Point = Point{x:2, y:3};
let mut pAdd:Point = p1 + p2;
However, if I use p1
and p2
one more time:
let mut pAdd:Point = p1 + p2;
let mut pAdd2:Point = p1 + p2;
I get the following error:
error: use of moved value p1
It turns out this is normal for Rust, since in this case variables are being moved and not copied. So, I thought all I had to do was to change the plus operator function a bit (references - &). And I did:
fn add(&self, rhs:&Point) -> Self::Output {
Point{x:(self.x + rhs.x), y:(self.y + rhs.y)}
}
But again this failed and I got this error:
error: method
add
has an incompatible type for trait: expected structPoint
, found &-ptr
What should I do?
EDIT: Thanks to @Grégory OBANOS I found that I can add #[derive(Copy, Clone)]
and this will make the struct copyable. However, I still don't understand why references don't work.