//! An implementation of a "trait object", //! which allows dynamic dispatch for implementing types, //! even allowing disparate types to be called, unlike a //! generic, which requires one specific implementation. //! //! Trait objects have some limitations (They must be "object-safe"): //! * Methods can not return `Self` //! * Methods can not have generic type parameters /// The base trait definition pub trait Draw { fn draw(&self); } /// A struct able to utilize the "trait object", via the Box type pub struct Screen { pub components: Vec>, } /// A method able to call the draw method on any objects /// implementing the Draw "trait object" impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } pub struct Button { pub width: u32, pub height: u32, pub label: String, } impl Draw for Button { fn draw(&self) { // code to actually draw a button } } #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2 + 2, 4); } }