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