通过例子学习Rust

31 操作符重载

在 Rust 语言中,许多运算符(Operators)都能通过接口(Traits)重载。这是因为运算符只是方法调用的语法糖。 例如,a + b 被当作 a.add(&b) 处理。这里的 add 方法是接口 Add 的一部分,所有 Add 接口的实现者都能使用 + 运算符。

struct Foo; struct Bar; #[deriving(Show)] struct FooBar; #[deriving(Show)] struct BarFoo; // The `Add<T, U>` trait needs two generic parameters: // * T is the type of the RHS summand, and // * U is the type of the sum // This block implements the operation: Foo + Bar = FooBar impl Add<Bar, FooBar> for Foo { fn add(self, _rhs: Bar) -> FooBar { println!("> Foo.add(&Bar) was called"); FooBar } } // Addition can be implemented in a non-commutative way // This block implements the operation: Bar + Foo = BarFoo impl Add<Foo, BarFoo> for Bar { 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); }

完整的可重载运算符接口列表可参见:ops