5.33.运算符和重载

Rust允许有限形式的运算符重载。这里有特定的运算符可以被重载。为了支持一个类型间特定的运算符,这里有一个你可以实现的特定的特性,它接着重载运算符。

例如,+运算符可以通过Add特性重载:

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 }
    }
}

fn main() {
    let p1 = Point { x: 1, y: 0 };
    let p2 = Point { x: 2, y: 3 };

    let p3 = p1 + p2;

    println!("{:?}", p3);
}

main中,我们可以对我们的两个Point+号,因为我们已经为Point实现了Add

这里有一系列可以这样被重载的运算符,并且所有与之相关的特性都在std::ops模块中。查看它的文档来获取完整的列表。

实现这些特性要遵循一个模式。让我们仔细看看Add

pub trait Add<RHS = Self> {
    type Output;

    fn add(self, rhs: RHS) -> Self::Output;
}

这里总共涉及到3个类型:你impl Add的类型,RHS,它默认是Self,和Output。对于一个表达式let z = x + yxSelf类型的,yRHS,而zSelf::Output类型。

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

    fn add(self, rhs: i32) -> f64 {
        // add an i32 to a Point and get an f64
    }
}

将允许你这样做:

let p: Point = // ...
let x: f64 = p + 2i32;
文章导航