Add, Mul, …
Operator overloading is implemented via traits in std::ops:
1. #[derive(Debug, Copy, Clone)]
2. struct Point { x: i32, y: i32 }
4. impl std::ops::Add for Point {
5. type Output = Self;
7. fn add(self, other: Self) -> Self {
8. Self {x: self.x + other.x, y: self.y + other.y}
9. }
10. }
12. fn main() {
13. let p1 = Point { x: 10, y: 20 };
14. let p2 = Point { x: 100, y: 200 };
15. println!("{:?} + {:?} = {:?}", p1, p2, p1 + p2);
16. }
Discussion points:
- You could implement
Addfor&Point. In which situations is that useful? - Answer:
Add:addconsumesself. If typeTfor which you are overloading the operator is notCopy, you should consider overloading the operator for&Tas well. This avoids unnecessary cloning on the call site. - Why is
Outputan associated type? Could it be made a type parameter? - Short answer: Type parameters are controlled by the caller, but associated types (like
Output) are controlled by the implementor of a trait.
