use std::vec; fn main() { let screen = Screen { components: vec![ Box::new(SelectBox { width: 75, height: 10, options: vec![ String::from("Yes"), String::from("Maybe"), String::from("No"), ], }), Box::new(Button { width: 50, height: 10, label: String::from("OK"), }), ], }; screen.run(); } pub trait Draw { fn draw(&self); } pub struct Screen { pub components: Vec<Box<dyn Draw>>, } impl Screen { pub fn run(&self) { for component in self.components.iter() { component.draw(); } } } //----------使用泛型就是如下代码,但是泛型只能是一种类型 // pub struct Screen<T: Draw> { // pub components: Vec<T>, // } // impl<T> Screen<T> // where // T: Draw, // { // 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) { //todo } } struct SelectBox { pub width: u32, pub height: u32, options: Vec<String>, } impl Draw for SelectBox { fn draw(&self) { //todo!() } }
22 面向对象编程特性
最新推荐文章于 2024-07-27 14:04:15 发布