运算符重载

在 Rust 中,许多运算符可以通过 traits 进行重载。也就是说,一些运算符可以根据其输入参数完成不同的任务。这是可能的,因为运算符是方法调用的语法糖。例如,a + b 中的 + 运算符会调用 add 方法(如 a.add(b))。这个 add 方法是 Add trait 的一部分。因此,+ 运算符可以被任何实现了 Add trait 的类型使用。

可以在 core::ops 中找到重载运算符的 traits 列表,例如 Add

use std::ops;

struct Foo;
struct Bar;

#[derive(Debug)]
struct FooBar;

#[derive(Debug)]
struct BarFoo;

// The `std::ops::Add` trait is used to specify the functionality of `+`.
// Here, we make `Add<Bar>` - the trait for addition with a RHS of type `Bar`.
// The following block implements the operation: Foo + Bar = FooBar
impl ops::Add<Bar> for Foo {
    type Output = FooBar;

    fn add(self, _rhs: Bar) -> FooBar {
        println!("> Foo.add(Bar) was called");

        FooBar
    }
}

// By reversing the types, we end up implementing non-commutative addition.
// Here, we make `Add<Foo>` - the trait for addition with a RHS of type `Foo`.
// This block implements the operation: Bar + Foo = BarFoo
impl ops::Add<Foo> for Bar {
    type Output = BarFoo;

    fn add(self, _rhs: Foo) -> BarFoo {
        println!("> Bar.add(Foo) was called");

        BarFoo
    }
}

fn main() {
    println!("Foo + Bar = {:?}", Foo + Bar);
    println!("Bar + Foo = {:?}", Bar + Foo);
}

另请参阅

Add, 语法索引