一、面向对象语言特性
// 平均值
pub struct AveragedCollection {
list: Vec<i32>, //私有字段
average:f64 //私有字段
}
impl AveragedCollection {
// add方法
pub fn add(&mut self,value:i32) {
self.list.push(value);
self.update_average();
}
// remove方法
pub fn remove(&mut self) -> Option<i32> {
let result = self.list.pop();
match result {
Some(value) => {
self.update_average();
Some(value)
},
None => None,
}
}
// average方法
pub fn average(&self) -> f64 {
self.average
}
// update
fn update_average(&mut self) {
let total :i32 = self.list.iter().sum();
self.average = total as f64 / self.list.len() as f64;
}
}
fn main() {
}
二、使用Trait对象存储不同类型的值
lib.rs定义
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();
}
}
}
// 定义button结构体
pub struct Button {
pub width:u32,
pub height:u32,
pub label:String,
}
// 为button实现draw这个trait
impl Draw for Button {
fn draw(&self) {
//绘制一个按钮
}
}
main.rs定义
use concurrent::Draw;
use concurrent::{Button,Screen};
// 定义选择框
struct SelectBox {
width:u32,
height:u32,
options:Vec<String>,
}
// 实现Draw trait
impl Draw for SelectBox {
fn draw(&self) {
// 绘制一个选择框
}
}
fn main() {
// 初始化screen
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();
}
clone这个就是对象不安全例子