演算子

Operators

Rustのオペレーターは、std::opsで定義されている。 演算子オーバーロードは、対応するtraitを実装する。

Add +

infix operator

定義

pub trait Add<Rhs = Self> {
    type Output;
    pub fn add(self, rhs: Rhs) -> Self::Output;
}
  • Rhs: RustはtraitもGenericパラメーターを持つことができ、デフォルト型も指定できる
  • type Output: 関連型

Example

use std::ops::*;

#[derive(Debug)]
struct Point(u32);

impl Add for Point {
    type Output = Self;
    fn add(self, rhs: Self) -> Self {
        Point(self.0 + rhs.0)
    }
}
impl Add<u32> for Point {
    type Output = Self;
    fn add(self, rhs: u32) -> Self {
        Point(self.0 + rhs)
    }
}

fn main() {
    let p1 = Point(5);
    let p2 = Point(3);
    dbg!(p1 + p2); // 8

    let p1 = Point(5);
    let p2 = Point(3);
    dbg!(p1 + p2 + 10_u32); // 18
}