본문 바로가기
Rust

[Rust] Trait 예제 (44일차)

by 꾸압 2023. 1. 27.

 

<예제 코드_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>

 

 

댓글