4.2 从 OOP 到 Rust

从 OOP 到 Rust — Comprehensive Rust

译文 · 基于 Comprehensive Rust

原文链接: https://google.github.io/comprehensive-rust/idiomatic/polymorphism/from-oop-to-rust.html

4.2 从 OOP 到 Rust

  • 继承是 OOP 作为范式取得成功的关键。数十年来,大量成功的软件工程以继承作为业务逻辑的核心。

  • 那么 Rust 为何回避继承?

  • 我们如何从基于继承的解题方式转向 Rust 的做法?

  • 在 Rust 中如何表示异构集合?

  • 本节将讨论:如何从 Java、C++ 等 OOP 语言中「用类型做多态解题」的思路,转向 Rust 基于 trait 的多态方式。

  • 会有差异,但也有许多共通之处——尤其是与现代 OOP 开发标准相比。请保持开放心态。


4.2.1 继承

01-继承 — Comprehensive Rust

4.2.2 Rust 为何没有继承?

02-Rust 为何没有继承?— Comprehensive Rust

4.2.3 从 Rust 视角看继承

03-从 Rust 视角看继承 — Comprehensive Rust

4.2.4 Rust 中的「继承」与父 Trait

04-Rust 中的「继承」与父 Trait — Comprehensive Rust

4.2.5 组合优于继承

05-组合优于继承 — Comprehensive Rust

4.2.6 Trait 对象与动态分发

06-Trait 对象与动态分发 — Comprehensive Rust

4.2.7 Dyn 兼容性

07-Dyn 兼容性 — Comprehensive Rust

4.2.8 泛型 vs Trait 对象

08-泛型 vs Trait 对象 — Comprehensive Rust

4.2.9 Trait 对象的局限

09-Trait 对象的局限 — Comprehensive Rust

4.2.10 异构集合

10-异构集合 — Comprehensive Rust

4.2.11 `Any` Trait

11-Any Trait — Comprehensive Rust

4.2.12 陷阱:过早伸手拿 `dyn Trait`

12-陷阱:过早伸手拿 dyn Trait — Comprehensive Rust

4.2.13 密封 Trait

13-密封 Trait — Comprehensive Rust

4.2.14 用枚举密封

14-用枚举密封 — Comprehensive Rust

4.2.15 可被用户扩展的多态 Trait

15-可被用户扩展的多态 Trait — Comprehensive Rust

4.2.16 解题:拆解问题

16-解题:拆解问题 — Comprehensive Rust

最后修改 August 11, 2026: 更新 (70a5af133)