运算符重载

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

会重载运算符的 trait(比如 Add 这种)可以在这里查看。

  1. use std::ops;
  2. struct Foo;
  3. struct Bar;
  4. #[derive(Debug)]
  5. struct FooBar;
  6. #[derive(Debug)]
  7. struct BarFoo;
  8. // `std::ops::Add` trait 用来指明 `+` 的功能,这里我们实现 `Add<Bar>`,它是用于
  9. // 把对象和 `Bar` 类型的右操作数(RHS)加起来的 `trait`。
  10. // 下面的代码块实现了 `Foo + Bar = FooBar` 这样的运算。
  11. impl ops::Add<Bar> for Foo {
  12. type Output = FooBar;
  13. fn add(self, _rhs: Bar) -> FooBar {
  14. println!("> Foo.add(Bar) was called");
  15. FooBar
  16. }
  17. }
  18. // 通过颠倒类型,我们实现了不服从交换律的加法。
  19. // 这里我们实现 `Add<Foo>`,它是用于把对象和 `Foo` 类型的右操作数加起来的 trait。
  20. // 下面的代码块实现了 `Bar + Foo = BarFoo` 这样的运算。
  21. impl ops::Add<Foo> for Bar {
  22. type Output = BarFoo;
  23. fn add(self, _rhs: Foo) -> BarFoo {
  24. println!("> Bar.add(Foo) was called");
  25. BarFoo
  26. }
  27. }
  28. fn main() {
  29. println!("Foo + Bar = {:?}", Foo + Bar);
  30. println!("Bar + Foo = {:?}", Bar + Foo);
  31. }

参见:

Add, 语法索引