Rust

[Rust lang] 87. trait objects, box

밍글링글링 2023. 3. 30.
728x90
/*
enum List {
    Content(i32, Box<List>),
    NoContent
}

fn main() {
    let my_list = List::Content(8786, Box::new(List::NoContent))
}
*/
trait Booky {}

struct Book {
    name: String
}
struct BigBook;

struct City {
    year_founded: i32
}

impl Booky for Book {}
impl Booky for BigBook {}
impl Booky for City {}

fn main() {
    let my_city = City {
        year_founded: 1989
    };

    let vec_of_booky_things: Vec<Box<dyn Booky>> = vec![
        Box::new(Book {
            name: "my book".to_string(),
        }),
        Box::new(BigBook),
        Box::new(my_city)
    ];
}
728x90

'Rust' 카테고리의 다른 글

[Rust lang] 89. function pointers  (0) 2023.03.30
[Rust lang] 88. three types of generics  (0) 2023.03.30
[Rust lang] 86. box  (0) 2023.03.30
[Rust lang] 85. clippy  (0) 2023.03.30
[Rust lang] 84. mutex  (0) 2023.03.30

댓글