1 Rust与面向对象编程
#![allow(dead_code)]trait Draw{fn draw(&self);}struct Screen {components: Vec<Box<Draw>>}impl Screen{fn run(&self){for item in self.components.iter(){item.draw();}}}struct Button {width: u32,height: u32,label: String,}impl Draw for Button {fn draw(&self) {}}struct SelectBox {width: u32,height: u32,options: Vec<String>,}impl Draw for SelectBox {fn draw(&self) {}}pub 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();}
3 特性对象
只有对象安全(object safe)的特性才可以用作特性对象。关于对象安全有一些复杂的规则,但通常仅考虑以下两点:特性的所有方法需要满足下述两个条件:
- 返回值类型不是Self
- 不带泛型参数
