Traits
๋ฌ์คํธ๋ ์ธํฐํ์ด์ค ์ฒ๋ผ ํธ๋ ์ดํธ๊ฐ ์๋ ํ์ ์ ์ถ์ํ ํ ์ ์์ต๋๋ค:
Rust lets you abstract over types with traits. Theyโre similar to interfaces:
trait Greet { fn say_hello(&self); } struct Dog { name: String, } // name ์์. ๊ณ ์์ด๋ ์ด์จ๋ ๋ฐ์ํ์ง ์์ต๋๋ค... // No name, cats won't respond to it anyway. struct Cat; impl Greet for Dog { fn say_hello(&self) { println!("Wuf, my name is {}!", self.name); } } impl Greet for Cat { fn say_hello(&self) { println!("Miau!"); } } fn main() { let pets: Vec<Box<dyn Greet>> = vec![ Box::new(Dog { name: String::from("Fido") }), Box::new(Cat), ]; for pet in pets { pet.say_hello(); } }