๋ฉ์๋
๋ฌ์คํธ์์ ์ ์ธ๋ ํ์
์ ๋ํด impl
๋ธ๋ก์ ํจ์๋ฅผ ์ ์ธํ์ฌ ๋ฉ์๋๋ฅผ ์ฐ๊ฒฐ ํ ์ ์์ต๋๋ค:
#[derive(Debug)] struct Race { name: String, laps: Vec<i32>, } impl Race { // ์์ ์ ์์, ์ ์ ๋ฉ์๋์ ๋๋ค. fn new(name: &str) -> Self { Self { name: String::from(name), laps: Vec::new() } } // self์ ๋ํ ๋ ์ ์ ๋น๋ฆผ ์ฝ๊ธฐ/์ฐ๊ธฐ ์ก์ธ์ค์ ๋๋ค. fn add_lap(&mut self, lap: i32) { self.laps.push(lap); } // self์ ๋ํ ๊ณต์ ๋ฐ ์ฝ๊ธฐ ์ ์ฉ ๋น๋ฆผ ์ก์ธ์ค์ ๋๋ค. fn print_laps(&self) { println!("๋ฉ ํ์ {}ํ, {} ๊ฒฝ๊ธฐ:", self.laps.len(), self.name); for (idx, lap) in self.laps.iter().enumerate() { println!("{idx}๋ฉ: {lap}์ด"); } } // self์ ๋ ์ ์ ์์ ๊ถ fn finish(self) { let total: i32 = self.laps.iter().sum(); println!("{} ๋ ์ด์ค ์ข ๋ฃ, ์ด ๋ฉ ์๊ฐ: {}", self.name, total); } } fn main() { let mut race = Race::new("๋ชจ๋์ฝ ๊ทธ๋ํ๋ฆฌ"); race.add_lap(70); race.add_lap(68); race.print_laps(); race.add_lap(71); race.print_laps(); race.finish(); // race.add_lap(42); }
The self
arguments specify the โreceiverโ - the object the method acts on. There are several common receivers for a method:
&self
: ํธ์ถ์๋ก๋ถํฐ ๊ณต์ ๊ฐ๋ฅํ ๋ถ๋ณ ์ฐธ์กฐ ๋ฐฉ์์ผ๋ก ๊ฐ์ฒด๋ฅผ ๋น๋ ค์ด์ ๋ํ๋ ๋๋ค. ๊ฐ์ฒด๋ ๋ฉ์๋ ํธ์ถ ๋ค์๋ ์ฌ์ฉ๋ ์ ์์ต๋๋ค.&mut self
: ํธ์ถ์๋ก๋ถํฐ ์ ์ผํ ๊ฐ๋ณ ์ฐธ์กฐ ๋ฐฉ์์ผ๋ก ๊ฐ์ฒด๋ฅผ ๋น๋ ค์ด์ ๋ํ๋ ๋๋ค. ๊ฐ์ฒด๋ ๋ฉ์๋ ํธ์ถ ๋ค์๋ ์ฌ์ฉ๋ ์ ์์ต๋๋ค.self
: ํธ์ถ์๋ก๋ถํฐ ๊ฐ์ฒด์ ์์ ๊ถ์ ๊ฐ์ ธ์ค๊ณ ๊ฐ์ฒด๋ ํธ์ถ์๋ก๋ถํฐ ๋ฉ์๋๋ก ์ด๋๋ฉ๋๋ค. ๋ฉ์๋๊ฐ ๊ฐ์ฒด๋ฅผ ์์ ํ๊ฒ ๋๋ฉฐ ๋ฐ๋ผ์ ๋ช ์์ ์ผ๋ก ์์ ๊ถ์ ๋ค๋ฅธ ๊ณณ์ผ๋ก ์ ๋ฌํ์ง ์๋๋ค๋ฉด ๋ฉ์๋ ์ข ๋ฃ์ ํจ๊ป ๊ฐ์ฒด๋ drop(ํด์ )๋ฉ๋๋ค.mut self
: same as above, but the method can mutate the object.- ๋ฆฌ์๋ฒ ์์: ๊ตฌ์กฐ์ฒด์ ์ ์ ๋ฉ์๋๊ฐ ๋ฉ๋๋ค. ์ฃผ๋ก ์์ฑ์๋ฅผ ๋ง๋ค๋ ์ฌ์ฉํ๊ฒ ๋๋ฉฐ, ์์ฑ์๋ ํํ
new
๋ผ๊ณ ์ด๋ฆ๋ถ์ ๋๋ค.
This slide should take about 8 minutes.
ํค ํฌ์ธํธ:
- ๋ฉ์๋๋ฅผ ํจ์์ ๋น๊ตํ์ฌ ์๊ฐํ๋ ๊ฒ๋ ๋์์ด ๋ ์ ์์ต๋๋ค.
- ๋ฉ์๋๋ ๊ตฌ์กฐ์ฒด๋ ์ด๊ฑฐํ๊ณผ ๊ฐ์ ํ์
์ ์ธ์คํด์ค์์ ํธ์ถ ๋๋ฉฐ, ์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์(ํ๋ผ๋ฉํฐ)๋ ์ธ์คํด์ค๋ฅผ
self
๋ก ํ๊ธฐํฉ๋๋ค. - ๋ฉ์๋๋ฅผ ์ด์ฉํ๋ฉด receiver ๋ฌธ๋ฒ์ ์ฌ์ฉํ ์ ์๊ณ ์ฝ๋๋ฅผ ์ข๋ ์ฒด๊ณ์ ์ผ๋ก ์ ๋ฆฌํ ์ ์์ต๋๋ค. ๋ฉ์๋๋ค์ด ์์ธก ๊ฐ๋ฅํ ์์น์ ๋ชจ์ฌ ์์ผ๋ ์ฐพ๊ธฐ ์ฝ์ต๋๋ค.
- ๋ฉ์๋๋ ๊ตฌ์กฐ์ฒด๋ ์ด๊ฑฐํ๊ณผ ๊ฐ์ ํ์
์ ์ธ์คํด์ค์์ ํธ์ถ ๋๋ฉฐ, ์ฒซ๋ฒ์งธ ๋งค๊ฐ๋ณ์(ํ๋ผ๋ฉํฐ)๋ ์ธ์คํด์ค๋ฅผ
- ๋ฉ์๋ receiver์ธ
self
ํค์๋ ์ฌ์ฉ์ ์ธ๊ธํด ์ฃผ์๊ธฐ ๋ฐ๋๋๋ค.- ์์ ์ ๊ฒฝ์ฐ
self: &Self
์ ์ค์ธ ๋ฒ์ ์์ ์๋ ค์ฃผ๊ณ , ๊ตฌ์กฐ์ฒด์ ์ด๋ฆ์ ์ง์ ์ฌ์ฉํ๋ฉด ์ด๋ป๊ฒ ๋๋์ง ๋ณด์ฌ์ฃผ๋ ๊ฒ๋ ์ข์ต๋๋ค. impl
๋ธ๋ก ๋ด๋ถ์์๋Self
๊ฐ ํด๋น ํ์ ์ ์ด๋ฆ ๋์ฉ์ผ๋ก ์ฌ์ฉ๋ ์ ์์์ ์๋ ค์ฃผ์ธ์.- ๊ตฌ์กฐ์ฒด์ ํ๋๋ฅผ ์ ๊ทผํ ๋ ์ ํ๊ธฐ๋ฅผ ์ฌ์ฉํ๋ฏ์ด
self
์ ์ ํ๊ธฐ๋ฅผ ์ฌ์ฉํ์ฌ ๊ฐ๋ณ ํ๋๋ค์ ์ ๊ทผํ ์ ์์ต๋๋ค. - This might be a good time to demonstrate how the
&self
differs fromself
by trying to runfinish
twice. self
๋ฅผ ์ฌ์ฉํ๋ ์ด๊ฐ์ ๋ณํ๋ค ์ธ์๋Box<Self>
์ ๊ฐ์ด ๋ฆฌ์๋ฒ ํ์ ์ผ๋ก ํ์ฉ๋๋ ํน๋ณํ ๋ํผ ํ์ ์ด ์์ต๋๋ค.
- ์์ ์ ๊ฒฝ์ฐ