Operators and Overloading

https://doc.rust-lang.org/book/operators-and-overloading.html

新たに定義した型に対して+を定義できる。

use std::ops::Add;

#[derive(Debug)]
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 }
    }
}

impl Add<i32> for Point {
    type Output = f64;

    fn add(self, rhs: i32) -> f64 {
        (self.x + self.y + rhs) as f64
    }
}

fn main() {
    let p1 = Point { x: 1, y: 0 };
    let p2 = Point { x: 2, y: 3 };
    let p3 = p1 + p2;
    println!("{:?}", p3);

    let p: Point = Point { x: 1, y: 1 };
    let x: f64 = p + 2i32;
    println!("{}", x);
}
$ cargo run
    Finished debug [unoptimized + debuginfo] target(s) in 0.0 secs
     Running `target/debug/4_32_operators_and_overloding`
Point { x: 3, y: 3 }
4