包龙星

爹,我要继承(Inheritance)你的《吵架秘籍》!

包有为

十三叔,Rust 里没有“继承”这个概念哦。但是我们可以用 Trait 来实现类似的效果(Polymorphism)。

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();
        }
    }
}
🎨

动手时刻:百家争鸣

使用 Trait Object 实现多态。

  1. 定义 Trait Speak,包含方法 say(&self)
  2. 定义结构体 DogCat,分别实现 Speak
  3. 创建一个 Vec<Box<dyn Speak>>
  4. 把一只狗和一只猫放进去。
  5. 遍历列表,调用 say
查看参考答案 (点击揭榜)

trait Speak {
    fn say(&self);
}

struct Dog;
struct Cat;

impl Speak for Dog {
    fn say(&self) { println!("汪汪!"); }
}

impl Speak for Cat {
    fn say(&self) { println!("喵喵!"); }
}

fn main() {
    let animals: Vec<Box<dyn Speak>> = vec![
        Box::new(Dog),
        Box::new(Cat),
    ];

    for animal in animals {
        animal.say();
    }
}
                    

成就解锁:【万物皆空】 🧘