μ°μ°μ
μ°μ°μ μ€λ²λ‘λλ 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
μ λν μ μκ² ν΄ μ€λλ€.