Methods

๋Ÿฌ์ŠคํŠธ๋Š” ๋ฉ”์„œ๋“œ(ํŠน์ • ํƒ€์ž…๊ณผ ๊ด€๊ณ„๋œ ๊ฐ„๋‹จํ•œ ํ•จ์ˆ˜)๋ฅผ ๊ฐ€์ง‘๋‹ˆ๋‹ค. ๋ฉ”์„œ๋“œ์˜ ์ฒซ๋ฒˆ์งธ ์ธ์ˆ˜๋Š” ํ˜ธ์ถœ๋ถ€ ํƒ€์ž…์˜ ์ธ์Šคํ„ด์Šค ์ž…๋‹ˆ๋‹ค.(self, this)

Rust has methods, they are simply functions that are associated with a particular type. The first argument of a method is an instance of the type it is associated with:

// ๊ตฌ์กฐ์ฒด ์„ ์–ธ์ž…๋‹ˆ๋‹ค.
struct Rectangle {
    width: u32,
    height: u32,
}

// ๊ตฌ์กฐ์ฒด์— ๊ตฌํ˜„๋œ ๋ฉ”์„œ๋“œ ๋“ค์ž…๋‹ˆ๋‹ค. 
// ๊ตฌ์กฐ์ฒด ์ž์ฒด์—๋Š” ๋ฐ์ดํ„ฐ๋งŒ ์„ ์–ธ์ด ๋˜์–ด impl ํ‚ค์›Œ๋“œ๋กœ ํ•ด๋‹น ๊ตฌ์กฐ์ฒด์— ๋ฉ”์„œ๋“œ๋ฅผ ์„ ์–ธ/์—ฐ๊ฒฐ ํ•ด์ฃผ๋Š” ๋ฌธ๋ฒ• ๊ตฌ์กฐ์ž…๋‹ˆ๋‹ค.
// ์ฒซ๋ฒˆ์งธ ์ธ์ˆ˜๋Š” ํ•ด๋‹น ๊ตฌ์กฐ์ฒด ์ž์‹ (self)์ž…๋‹ˆ๋‹ค.  
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 };
    // ๋ฉ”์„œ๋“œ๋Š” .์œผ๋กœ ํ˜ธ์ถœํ•˜๋ฉฐ area์˜ self.width๋Š” 10, self.height๋Š” 5์ž…๋‹ˆ๋‹ค.
    println!("old area: {}", rect.area()); 
    rect.inc_width(5);
    println!("new area: {}", rect.area());
}
  • ์˜ค๋Š˜๊ณผ ๋‚ด์ผ ๊ฐ•์˜์—์„œ ๋” ๋งŽ์€ ๋ฉ”์„œ๋“œ ์‚ฌ์šฉ๋ฒ•์„ ๋‹ค๋ฃฐ ๊ฒƒ์ž…๋‹ˆ๋‹ค.
  • We will look much more at methods in todayโ€™s exercise and in tomorrowโ€™s class.