集册 Rust 编程语言 运算符和重载

运算符和重载

—— 运算符与重载

欢马劈雪     最近更新时间:2020-08-04 05:37:59

90

operators-and-overloading.md
commit 6ba952020fbc91bad64be1ea0650bfba52e6aab4

Rust 允许有限形式的运算符重载。特定的运算符可以被重载。要支持一个类型间特定的运算符,你可以实现一个的特定的重载运算符的trait。

例如,+运算符可以通过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<Output=Point>

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

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

# mod foo {
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类型。

# struct Point;
# use std::ops::Add;
impl Add<i32> for Point {
    type Output = f64;

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

将允许你这样做:

let p: Point = // ...
let x: f64 = p + 2i32;

在泛型结构体中使用运算符 trait

现在我们知道了运算符 trait 是如何定义的了,我们可以更通用的定义来自[trait 章节]()的HasArea trait 和Square结构体:

use std::ops::Mul;

trait HasArea<T> {
    fn area(&self) -> T;
}

struct Square<T> {
    x: T,
    y: T,
    side: T,
}

impl<T> HasArea<T> for Square<T>
        where T: Mul<Output=T> + Copy {
    fn area(&self) -> T {
        self.side * self.side
    }
}

fn main() {
    let s = Square {
        x: 0.0f64,
        y: 0.0f64,
        side: 12.0f64,
    };

    println!("Area of s: {}", s.area());
}
展开阅读全文