Rust - Operator Overloading


Some operators may be overloaded in rust by implementing the corresponding trait in std::ops

Add

use std::ops::Add;

#[derive(Debug, PartialEq, Copy, Clone)]
struct Point{ x: i32, y: i32 }

impl Add for Point {
    type Output = Point;

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

fn main() {
    assert_eq!(
        Point{ x: 3, y: -2 } + Point{ x: 2, y: -3 },
        Point{ x: 5, y: -5 }
    );
}