頭條地址:https://www.ixigua.com/i677586170644791348...
B站地址:https://www.bilibili.com/video/av81202308/
github地址:https://github.com/anonymousGiga/learn_rus...
1、封裝
(1)封裝的思想:物件的實現細節不能被使用物件的程式碼獲取到。
(2)在Rust中,使用pub關鍵字來標記模組、型別、函式和方法是公有的,預設情況下一切都是私有的。
例子:
(1) mkdir learn_oo
(2) cd learn_oo
(3) 編輯Cargo.toml:
[workspace]
members = [
"getaver",
"main",
]
(4) cargo new getaver –lib
(5) 編輯 getaver/src/lib.rs,程式碼如下:
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 remove(&mut self) -> Option<i32> {
let result = self.list.pop();
match result {
Some(value) => {
self.update_average();
Some(value)
},
None => None,
}
}
pub fn average(&self) -> f64 {
self.aver
}
fn update_average(&mut self) {
let total: i32 = self.list.iter().sum();
self.aver = total as f64 / self.list.len() as f64;
}
}
(6) cargo new main
(7) 編輯main/Cargo.toml,新增:
[dependencies]
getaver = {path = "../getaver"}
(8) 編輯main/src/main.rs,程式碼如下:
use getaver::AverCollect;
fn main() {
let mut a = getaver::AverCollect::new();
a.add(1);
println!("average value = {}", a.average());
a.add(2);
println!("average value = {}", a.average());
a.add(3);
println!("average value = {}", a.average());
a.remove();
println!("average value = {}", a.average());
println!("Hello, world!");
}
2、繼承
Rust不支援繼承。但是Rust可以透過trait進行行為共享。trait的知識點此處不進行重複。
本作品採用《CC 協議》,轉載必須註明作者和本文連結