疊代器
運算子超載會透過 std::ops
: 內的特徵實作:
Speaker Notes
This slide should take about 10 minutes.
討論要點:
- You could implement
Add
for&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.
- Short answer: Function type parameters are controlled by the caller, but associated types (like
- 您可以針對兩種不同型別實作
Add
,舉例來說,impl Add<(i32, i32)> for Point
會將元組新增至Point
。