๋ฉ”์„œ๋“œ

๋ฉ”์„œ๋“œ๋Š” ํŠน์ • ํƒ€์ž…๊ณผ ์—ฐ๊ฒฐ๋œ ํ•จ์ˆ˜์ž…๋‹ˆ๋‹ค. ๋ฉ”์„œ๋“œ์˜ self ์ธ์ž๊ฐ€ ๊ทธ ๋ฉ”์„œ๋“œ๊ฐ€ ์—ฐ๊ฒฐ๋œ ์ธ์Šคํ„ด์Šค์˜ ํƒ€์ž…์ž…๋‹ˆ๋‹ค:

struct Rectangle {
    width: u32,
    height: u32,
}

impl Rectangle {
    fn area(&self) -> u32 {
        self.width * self.height
    }

    fn inc_width(&mut self, delta: u32) {
        self.width += delta;
    }
}

fn main() {
    let mut rect = Rectangle { width: 10, height: 5 };
    println!("old area: {}", rect.area());
    rect.inc_width(5);
    println!("new area: {}", rect.area());
}
  • ์˜ค๋Š˜๊ณผ ๋‚ด์ผ ๊ฐ•์˜์—์„œ ๋” ๋งŽ์€ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ๋ฒ•์„ ๋‹ค๋ฃฐ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
  • Rectangle::new ์ƒ์„ฑ์ž๋ฅผ ์ถ”๊ฐ€ํ•˜๊ณ  ์ด๋ฅผ main์—์„œ ํ˜ธ์ถœํ•ฉ๋‹ˆ๋‹ค:

    fn new(width: u32, height: u32) -> Rectangle {
        Rectangle { width, height }
    }
  • _๊ธฐ์ˆ ์ _์œผ๋กœ ์ด์•ผ๊ธฐ ํ•˜์ž๋ฉด, ๋Ÿฌ์ŠคํŠธ๋Š” ์ปค์Šคํ…€ ์ƒ์„ฑ์ž๋ฅผ ์ง€์›ํ•˜์ง€ ์•Š์Šต๋‹ˆ๋‹ค. ์ •์  ๋ฉ”์†Œ๋“œ๋ฅผ ์‚ฌ์šฉํ•˜๋Š” ๊ฒƒ์ด ๊ตฌ์กฐ์ฒด๋ฅผ ์ดˆ๊ธฐํ™” ํ•˜๋Š” ์ผ๋ฐ˜์ ์ธ ๋ฐฉ๋ฒ•์ž…๋‹ˆ๋‹ค (๋ฌผ๋ก  ์ด๊ฒƒ์ด ๊ฐ•์ œ๋˜์ง€๋Š” ์•Š์Šต๋‹ˆ๋‹ค). ์ง„์งœ ์ƒ์„ฑ์ž์ธ Rectangle { width, height }๋ฅผ ์ง์ ‘ ํ˜ธ์ถœํ•  ์ˆ˜๋„ ์žˆ์Šต๋‹ˆ๋‹ค. ์ž์„ธํ•œ ๋‚ด์šฉ์€ Rustnomicon์„ ์ฐธ์กฐํ•˜์„ธ์š”.

  • Rectangle::square(width: u32) ์ƒ์„ฑ์ž๋ฅผ ์ถ”๊ฐ€ํ•˜์—ฌ ์ƒ์„ฑ์ž๊ฐ€ ์ž„์˜์˜ ๋งค๊ฐœ๋ณ€์ˆ˜๋ฅผ ์‚ฌ์šฉํ•  ์ˆ˜ ์žˆ์Œ์„ ๋ณด์ž…์‹œ๋‹ค.