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();
    }
}