运算符
运算符重载是通过 std::ops 中的特征实现的:
1. #[derive(Debug, Copy, Clone)]
2. struct Point {
3. x: i32,
4. y: i32,
5. }
7. impl std::ops::Add for Point {
8. type Output = Self;
10. fn add(self, other: Self) -> Self {
11. Self { x: self.x + other.x, y: self.y + other.y }
12. }
13. }
15. fn main() {
16. let p1 = Point { x: 10, y: 20 };
17. let p2 = Point { x: 100, y: 200 };
18. println!("{:?} + {:?} = {:?}", p1, p2, p1 + p2);
19. }
This slide should take about 10 minutes.
讨论点:
- You could implement
Addfor&Point. In which situations is that useful? - 回答:
Add:add会耗用self。如果您的运算符重载对象 (即类型T)不是Copy,建议您也为&T重载运算符。这可避免调用点上存在不必要的 克隆任务。 - 为什么
Output是关联类型?可将它用作该方法的类型形参吗? - Short answer: Function type parameters are controlled by the caller, but associated types (like
Output) are controlled by the implementer of a trait. - 您可以针对两种不同类型实现
Add,例如,impl Add<(i32, i32)> for Point会向Point中添加元组。
