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.
- Short answer: Function type parameters are controlled by the caller, but associated types (like
Add
๋ฅผ ์ด์ฉํด์ ์๋ก ๋ค๋ฅธ ๋ ๊ฐ์ ํ์ ์ ๋ํ ์๋ ์์ต๋๋ค. ์๋ฅผ ๋ค์ดimpl Add<(i32, i32)> for Point
๋ ํํ์Point
์ ๋ํ ์ ์๊ฒ ํด ์ค๋๋ค.