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.