Rust 面向对象:祖传秘方
Rust 不是传统的 OOP 语言(没有 Class),但它受到 OOP 思想的影响。
🎁 封装 (Encapsulation)
通过 pub 关键字控制字段和方法的可见性。
pub struct AveragedCollection {
list: Vec<i32>, // 私有字段,外部改不了
average: f64,
}
impl AveragedCollection {
pub fn add(&mut self, value: i32) {
self.list.push(value);
self.update_average();
}
// ...
}
🧬 继承?用 Trait 代替!
Rust 不支持类继承,但支持接口继承(Trait)。你可以定义默认行为。
pub trait Summary {
fn summarize(&self) -> String {
String::from("(Read more...)") // 默认实现
}
}
🎭 多态 (Trait Objects)
如果你想在一个列表里放不同类型的对象,只要它们实现了同一个 Trait。
pub trait Draw {
fn draw(&self);
}
pub struct Screen {
// 这里的 Box 就是 Trait Object
pub components: Vec<Box<dyn Draw>>,
}
impl Screen {
pub fn run(&self) {
for component in self.components.iter() {
component.draw();
}
}
}