Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust 面向對象編程

Rust 中的 OOP 概念、設計模式、封裝與多態。

📚 OOP 介紹

Rust 中的 OOP

🎯 主要概念

封裝 (Encapsulation)

  • 使用 struct 和 impl 塊
  • pub 可見性控制

繼承 (Inheritance)

  • Trait 作為接口
  • Trait 默認實現
  • Trait Bounds

多態 (Polymorphism)

💡 Rust OOP vs 傳統 OOP

相似之處:

  • 封裝:struct + impl
  • 多態:trait objects + generics
  • 接口:traits

不同之處:

  • 無類繼承(用 trait 和組合)
  • 無 null(用 Option)
  • 無 this(用 self)

推薦做法:

  • 優先使用組合而非繼承
  • 使用 Trait 定義接口
  • 泛型優於 Trait Objects(性能更好)

最後更新: 2025-12-01