Rust 学习笔记 23:面向对象特性 (Object Oriented Features)

Rust 学习笔记 23:面向对象特性 (Object Oriented Features) “The problem with object-oriented languages is they’ve got all this implicit environment that they carry around with them. You wanted a banana but you got a gorilla holding the banana and the entire jungle.” – Joe Armstrong Rust 是面向对象语言吗?这取决于你对 OOP 的定义。 如果定义是"封装、继承、多态",那么 Rust: 封装:有。struct 和 impl,以及 pub 关键字。 继承:没有。Rust 没有任何继承机制(Struct 不能继承 Struct)。 多态:有。通过泛型(静态多态)和 Trait Objects(动态多态)。 1. Trait Objects (动态分发) 我们在泛型那一章学过用 Trait Bound 实现多态: 1fn draw<T: Draw>(item: T) { item.draw(); } 这种是静态分发 (Static Dispatch)。编译器会为每种具体的 T 生成一份代码。优点是快,缺点是 Vec<T> 里的所有元素必须是同一种类型。 ...

2026-01-20 · 2 min · 215 words · 老墨