疊代器

運算子超載會透過 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);
}
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.
  • 您可以針對兩種不同型別實作 Add,舉例來說, impl Add<(i32, i32)> for Point 會將元組新增至 Point