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 · 老墨

Rust 学习笔记 15:Traits (特质)

Rust 学习笔记 15:Traits (特质) “If it walks like a duck and quacks like a duck, it must be a Trait.” 在 Go 语言中,接口 (Interface) 是隐式实现的。只要你的方法签名对上了,你就实现了接口。 在 Rust 中,Traits (特质) 必须要显式实现 (impl Trait for Type)。 1. 定义与实现 Trait 定义一个 Summary Trait: 1pub trait Summary { 2 fn summarize(&self) -> String; 3} 为 NewsArticle 和 Tweet 实现它: 1impl Summary for Tweet { 2 fn summarize(&self) -> String { 3 format!("{}: {}", self.username, self.content) 4 } 5} 2. 默认实现 (Default Implementations) Trait 中可以提供默认实现,这有点像 Java 8 的 default method。 ...

2025-05-20 · 2 min · 286 words · 老墨