运算符重载
在 Rust 中,很多运算符可以通过 trait 来重载。也就是说,这些运算符可以根据它们的
输入参数来完成不同的任务。这之所以可行,是因为运算符就是方法调用的语法糖。例
如,a + b 中的 + 运算符会调用 add 方法(也就是 a.add(b))。这个 add 方
法是 Add trait 的一部分。因此,+ 运算符可以被任何 Add trait 的实现者使用。
会重载运算符的 trait(比如 Add 这种)可以在这里查看。
1. use std::ops;
3. struct Foo;
4. struct Bar;
6. #[derive(Debug)]
7. struct FooBar;
9. #[derive(Debug)]
10. struct BarFoo;
12. // `std::ops::Add` trait 用来指明 `+` 的功能,这里我们实现 `Add<Bar>`,它是用于
13. // 把对象和 `Bar` 类型的右操作数(RHS)加起来的 `trait`。
14. // 下面的代码块实现了 `Foo + Bar = FooBar` 这样的运算。
15. impl ops::Add<Bar> for Foo {
16. type Output = FooBar;
18. fn add(self, _rhs: Bar) -> FooBar {
19. println!("> Foo.add(Bar) was called");
21. FooBar
22. }
23. }
25. // 通过颠倒类型,我们实现了不服从交换律的加法。
26. // 这里我们实现 `Add<Foo>`,它是用于把对象和 `Foo` 类型的右操作数加起来的 trait。
27. // 下面的代码块实现了 `Bar + Foo = BarFoo` 这样的运算。
28. impl ops::Add<Foo> for Bar {
29. type Output = BarFoo;
31. fn add(self, _rhs: Foo) -> BarFoo {
32. println!("> Bar.add(Foo) was called");
34. BarFoo
35. }
36. }
38. fn main() {
39. println!("Foo + Bar = {:?}", Foo + Bar);
40. println!("Bar + Foo = {:?}", Bar + Foo);
41. }
