<예제 코드_1>
#![allow(dead_code)]
fn main() {
trait Animal {
fn eat(&self);
}
struct Herbivore;
struct Carnivore;
impl Animal for Herbivore {
fn eat(&self) {
println!("I eat plants");
}
}
impl Animal for Carnivore {
fn eat(&self) {
println!("I eat flesh");
}
}
let h = Herbivore;
h.eat();
}
[실행 결과]
$ I eat plants
<예제 코드_2>
fn main() {
trait Animal {
fn eat(&self);
}
struct Herbivore;
struct Carnivore;
impl Animal for Herbivore {
fn eat(&self) {
println!("I eat plants");
}
}
impl Animal for Carnivore {
fn eat(&self) {
println!("I eat flesh");
}
}
// Create a vector of animals:
let mut list: Vec<Box<dyn Animal>> = Vec::new();
let goat = Herbivore;
let dog = Carnivore;
list.push(Box::new(goat));
list.push(Box::new(dog));
// Calling eat() for all animals in the list:
for animal in &list {
animal.eat();
}
}
[실행 결과]
$ I eat plants
$ I eat flesh
<참조 1> https://www.educative.io/answers/what-is-the-dyn-keyword-in-rust
<참조 2>
'Rust' 카테고리의 다른 글
[Rust] 고급 Trait 예제 (46일차) (0) | 2023.01.29 |
---|---|
[Rust] Pattern : 여러 예제 (45일차) (0) | 2023.01.28 |
[Rust] 공유 상태 동시성 예제 (Shared State Concurrency, 43일차) (0) | 2023.01.26 |
[Rust] Concurrency : Message Passing 예제 (42일차) (0) | 2023.01.25 |
댓글