0

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 struct Point, 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.

DimChtz
  • 4,043
  • 2
  • 21
  • 39
  • 1
    You can (and should) derive Copy, Clone for Point – Grégory OBANOS Nov 03 '17 at 16:25
  • 1
    Okay thanks, I will search for "derive Copy, Clone". In the meantime do you know why my solution with references doesn't work? – DimChtz Nov 03 '17 at 16:28
  • playground: https://play.rust-lang.org/?gist=7831cf420a332bfedf7e71ef8f11fb76&version=stable – turbulencetoo Nov 03 '17 at 16:47
  • @turbulencetoo I already know it doesn't work. – DimChtz Nov 03 '17 at 16:54
  • Sorry for my short answer, as pointed out in the duplicate, you can implement Add for a reference, as shown in that playground : https://play.rust-lang.org/?gist=846cab2eef7ed74713ff2fd4d8e594a6&version=stable. You can't change a trait function signature, but you can change the types. – Grégory OBANOS Nov 03 '17 at 18:02

0 Answers0