Skip to content

Operator overloading not flexible enough? #21188

Closed
@SirVer

Description

@SirVer

I might just missing some informations here, but I have a hard time implementing a simple Point type that can be added:

use std::ops::{Add, Sub};

#[derive(Show)]
struct Point {
    x: f32,
    y: f32,
}

impl Add for Point {
    type Output = Point;
    fn add(self, other: Point) -> Point {
        Point{x: self.x + other.x, y: self.y + other.y}
    }
}

#[test]
fn point_to_point_addition() {
    let a = Point {x: 3f32, y: 5f32};
    let b = Point {x: -1f32, y: 5f32};
    let res = a + b;
    let res1 = b + a; // <- Error: use of moved value: `b` and `a`
}

That error makes sense to me, so I went ahead and tried implementing this for &'a Point.

impl<'a> Add for &'a Point {
    type Output = Point;
    fn add(self, other: &'a Point) -> Point {
        Point{x: self.x + other.x, y: self.y + other.y}
    }
}

#[test]
fn point_to_point_addition() {
    let a = &Point {x: 3f32, y: 5f32};
    let b = &Point {x: -1f32, y: 5f32};
    let res = a + b;
    let res1 = b + a;
    let res2 = a + b + b + a; // <- this now no longer works :(
}

But now chaining does no longer work since the Add returns a Point, not a &mut Point. Can somebody enlighten me about the correct way of solving this?

Another - maybe unrelated - issue I stumbled on is how to make Point + f32 do the same as f32 + Point.

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions