μ—°μ‚°μž

μ—°μ‚°μž μ˜€λ²„λ‘œλ“œλŠ” 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에 더할 수 있게 ν•΄ μ€λ‹ˆλ‹€.