Operator Overloading (Multiple Add operations)

Hi everyone,

I'm trying to do operators overloading on a Vector2 struct:

pub struct Vector2 {
    x:f64,
    y:f64
}

and the "Add" operator to add another Vector2 to self:

impl Add for Vector2 {
    type Output = Vector2;

    fn add(self, other: Vector2) -> Vector2 {
        Vector2 {
            x: self.x + other.x,
            y: self.y + other.y,
        }
    }
}

This works fine by:

let v1:Vector2 = Vector2(0.0, 0.0);
let v2:Vector2 = Vector2(1.0, 1.0);
let v3:Vector2 = v1 + v2;

Now, how do I implement another "Add" operator to add a float to self such as:

impl Add for Vector2 {
    type Output = Self;

    fn add(self, value: f64) -> Self {
        Self {
            x: self.x + value,
            y: self.y + value,
        }
    }
}

So I could do:

let v1:Vector2 = Vector2::new(0.0, 0.0);
let v2: Vector2 = v1 + 1.0; // {x:1.0, y:1.0}

Adding a second "Add" operator gives me a duplication error.
Is it possible to do this stuff?

Thanks!

The second impl block needs to be

impl Add<f64> for Vector2 {
    ...
}
1 Like

That was simple! :smile:

Thanks @asymmetrikon!

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.