rust_book_17_02/
rust-book-17-02.rs

1//! The example from [section 17.2 of the Rust book][0],
2//! modified to use `UnsizedVec` instead of `Vec<Box<_>>>`.
3//!
4//! [0]: https://doc.rust-lang.org/book/ch17-02-trait-objects.html
5
6#![allow(
7    dead_code,
8    internal_features, // for `unsized_fn_params`
9)]
10#![feature(allocator_api, ptr_metadata, unsized_fn_params)]
11
12use emplacable::by_value_str;
13use unsized_vec::{UnsizedVec, unsize_vec, unsized_vec};
14
15mod gui {
16    //! lib.rs
17
18    use unsized_vec::UnsizedVec;
19
20    pub trait Draw {
21        fn draw(&self);
22    }
23    pub struct Screen {
24        pub components: UnsizedVec<dyn Draw>,
25    }
26
27    impl Screen {
28        pub fn run(&self) {
29            for component in self.components.iter() {
30                component.draw();
31            }
32        }
33    }
34    pub struct Button {
35        pub width: u32,
36        pub height: u32,
37        pub label: Box<str>,
38    }
39
40    impl Draw for Button {
41        fn draw(&self) {
42            // code to actually draw a button
43        }
44    }
45}
46
47// main.rs
48use gui::Draw;
49
50struct SelectBox {
51    width: u32,
52    height: u32,
53    options: UnsizedVec<str>,
54}
55
56impl Draw for SelectBox {
57    fn draw(&self) {
58        // code to actually draw a select box
59    }
60}
61
62use gui::{Button, Screen};
63
64fn main() {
65    let screen = Screen {
66        components: unsize_vec![
67            SelectBox {
68                width: 75,
69                height: 10,
70                options: unsized_vec![
71                    by_value_str!("Yes"),
72                    by_value_str!("Maybe"),
73                    by_value_str!("No"),
74                ],
75            },
76            Button {
77                width: 50,
78                height: 10,
79                label: Box::<str>::from("OK"),
80            },
81        ],
82    };
83
84    screen.run();
85}