Rust面向对象
面向对象的特点:对象、封装、继承
- 对象: 数据和操作数据的过程
(1) Rust里面的结构体、枚举类型和impl块
- Rust中没有继承的概念,但是可以通过特征trait进行行为的共享
链接:🥰trait的继承
1 2 3 4 5 6 7 8 9 10 11
| trait A { fn sum() { } } struct xx {
} impl A for xxx {
}
|
对象
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| struct Dog{ name: String, }
impl Dog { fn print_name(&self) { println!("Dog name = {}",self.name); } }
fn main() { let d = Dog {name:String::from("wangcai")}; d.print_name(); }
|
封装
我们只知道有remove,add,new这些方法,但是他们被封装起来了
- 创建空文件夹
1 2 3
| mkdir learn cd learn vim Cargo.toml
|
- 在Cargo.toml中进行设置
1 2 3 4 5
| [workspace] members = [ "getaver", "main", ]
|
- 创建main文件夹
- 创建getaver文件夹
- 在getaver中写代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42
| #[cfg(test)] mod tests { #[test] fn it_works() { assert_eq!(2+2,4); } } pub struct AverCollect { list: Vec<i32>, aver: f64, }
impl AverCollect { pub fn new() -> AverCollect { AverCollect{ list: vec![], aver: 0.0, } } pub fn add(&mut self,value: i32) { self.list.push(value); self.update_average(); } pub fn average(&self) -> f64 { self.aver } pub fn remove(&mut self) -> Option<i32> { let result = self.list.pop(); match result { Some(value) => { self.update_average(); Some(value) }, None => None, } } fn update_average(&mut self) { let total: i32 = self.list.iter().sum(); self.aver = total as f64 /self.list.len() as f64; } }
|
- 在main里面调用对象
1 2 3 4 5
| [package] name = .... [dependencies] getacer = {path = "../getaver"}
|
- 在main函数中使用
1 2 3 4 5 6 7 8 9 10 11 12 13 14
| use getaver;
fn main() { let mut a = getaver::AverCollect::new();
a.add(1); println!("average = {}",a.average()); a.add(2); println!("average = {}",a.average()); a.add(3); println!("average = {}",a.average()); a.remove(); println!("average = {}",a.average()); }
|