Add
Mul ``…
运算符重载是通过 std::ops
中的特征实现的:
#[derive(Debug, Copy, Clone)] struct Point { x: i32, y: i32 } impl std::ops::Add for Point { type Output = Self; fn add(self, other: Self) -> Self { Self {x: self.x + other.x, y: self.y + other.y} } } fn main() { let p1 = Point { x: 10, y: 20 }; let p2 = Point { x: 100, y: 200 }; println!("{:?} + {:?} = {:?}", p1, p2, p1 + p2); }
讨论点:
- 您可以针对
&Point
实现Add
。此做法在哪些情况下可派上用场?- 回答:
Add:add
会耗用self
。如果您的运算符重载对象 (即类型T
)不是Copy
,建议您也为&T
重载运算符。这可避免调用点上存在不必要的 克隆任务。
- 回答:
- 为什么
Output
是关联类型?可将它用作该方法的类型形参吗?- 简答:函数类型形参是由调用方控管,但
Output
这类关联类型则由特征实现人员 控管。
- 简答:函数类型形参是由调用方控管,但
- 您可以针对两种不同类型实现
Add
,例如,impl Add<(i32, i32)> for Point
会向Point
中添加元组。