Iterators

์—ฐ์‚ฐ์ž ์˜ค๋ฒ„๋กœ๋“œ๋Š” 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์— ๋”ํ•  ์ˆ˜ ์žˆ๊ฒŒ ํ•ด ์ค๋‹ˆ๋‹ค.