Trait 定義與實作

最後更新


特徵(trait)描述「一種型別能做什麼」:先定義一組方法,再讓不同型別各自實作,就能用同樣的方式操作它們。

什麼是 trait


trait 是一份「能力清單」。例如「能被印出摘要」「能比較大小」「能被複製」。一個型別只要實作了某個 trait,就擁有那份清單上的能力。
會其他語言的讀者可以這樣對照:trait 接近 Java/C# 的 interface、Go 的 interface,但 Rust 的實作必須明確寫出 impl Trait for Type,不會自動符合;而且可以替既有的型別(包括 i32)補上新的 trait。

定義 trait


用 trait 關鍵字,裡面列出方法的簽名,以分號結尾、不寫內容。&self 代表方法透過借用取得呼叫它的值(見方法)。
範例:
  1. trait Summary {
  2. fn summarize(&self) -> String;
  3. }
  4. struct Article {
  5. title: String,
  6. words: usize,
  7. }
  8. impl Summary for Article {
  9. fn summarize(&self) -> String {
  10. format!("《{}》約 {} 字", self.title, self.words)
  11. }
  12. }
  13. fn main() {
  14. let a = Article { title: String::from("Rust 入門"), words: 3200 };
  15. println!("{}", a.summarize());
  16. }

輸出:
  1. 《Rust 入門》約 3200 字

為不同型別實作同一個 trait


同一個 trait 可以由許多型別實作,每個型別給出自己的版本。只要你的 crate 定義了這個 trait,也可以替標準庫的型別(如 i32、Vec<T>)實作它。
注意:要在別的模組呼叫 trait 的方法,該 trait 必須在作用域內(use 路徑::Summary;),否則編譯器會說找不到方法。
範例:
  1. trait Summary {
  2. fn summarize(&self) -> String;
  3. }
  4. struct Tweet {
  5. user: String,
  6. text: String,
  7. }
  8. enum Notice {
  9. Maintenance(u32),
  10. Release(String),
  11. }
  12. impl Summary for Tweet {
  13. fn summarize(&self) -> String {
  14. format!("@{}:{}", self.user, self.text)
  15. }
  16. }
  17. impl Summary for Notice {
  18. fn summarize(&self) -> String {
  19. match self {
  20. Notice::Maintenance(min) => format!("維護 {} 分鐘", min),
  21. Notice::Release(v) => format!("發布 {}", v),
  22. }
  23. }
  24. }
  25. impl Summary for i32 {
  26. fn summarize(&self) -> String {
  27. if *self >= 0 { format!("正數 {}", self) } else { format!("負數 {}", self) }
  28. }
  29. }
  30. fn main() {
  31. let t = Tweet { user: String::from("ferris"), text: String::from("你好") };
  32. println!("{}", t.summarize());
  33. println!("{}", Notice::Maintenance(30).summarize());
  34. println!("{}", Notice::Release(String::from("v2.0")).summarize());
  35. println!("{}", (-5).summarize());
  36. }

輸出:
  1. @ferris:你好
  2. 維護 30 分鐘
  3. 發布 v2.0
  4. 負數 -5

預設方法


trait 裡的方法可以直接寫出內容,成為預設實作(default implementation)。實作者不寫就沿用預設,寫了就覆寫。預設方法可以呼叫同一個 trait 的其他方法,所以常見的設計是:只要求實作一兩個核心方法,其餘方法用它們組合出來。
範例:
  1. trait Summary {
  2. fn author(&self) -> String;
  3. fn summarize(&self) -> String {
  4. format!("({} 的文章,點擊閱讀更多)", self.author())
  5. }
  6. }
  7. struct Post {
  8. by: String,
  9. }
  10. struct News {
  11. by: String,
  12. headline: String,
  13. }
  14. impl Summary for Post {
  15. fn author(&self) -> String {
  16. self.by.clone()
  17. }
  18. }
  19. impl Summary for News {
  20. fn author(&self) -> String {
  21. self.by.clone()
  22. }
  23. fn summarize(&self) -> String {
  24. format!("{}/{}", self.headline, self.author())
  25. }
  26. }
  27. fn main() {
  28. let p = Post { by: String::from("amy") };
  29. let n = News { by: String::from("ben"), headline: String::from("新版發布") };
  30. println!("{}", p.summarize());
  31. println!("{}", n.summarize());
  32. }

輸出:
  1. (amy 的文章,點擊閱讀更多)
  2. 新版發布/ben

編譯不過:漏實作必要的方法


沒有預設內容的方法是「必要方法」,impl 時一定要寫。漏了任何一個,這段無法編譯:
範例:
  1. trait Shape {
  2. fn area(&self) -> f64;
  3. fn name(&self) -> String;
  4. }
  5. struct Square(f64);
  6. impl Shape for Square {
  7. fn area(&self) -> f64 {
  8. self.0 * self.0
  9. }
  10. }
  11. fn main() {
  12. println!("{}", Square(2.0).area());
  13. }

輸出:
  1. error[E0046]: not all trait items implemented, missing: `name`
  2. --> main.rs:8:1
  3. |
  4. 3 | fn name(&self) -> String;
  5. | ------------------------- `name` from trait
  6. ...
  7. 8 | impl Shape for Square {
  8. | ^^^^^^^^^^^^^^^^^^^^^ missing `name` in implementation

孤兒規則


只能在「自己擁有 trait 或型別」時實作


孤兒規則(orphan rule):impl Trait for Type 只有在 trait 或型別至少有一個是你的 crate 定義的 時候才允許。你可以為自己的型別實作標準庫的 Display,也可以為 i32 實作自己的 Summary;但不能為標準庫的 Vec<i32> 實作標準庫的 Display。
這條規則確保不會有兩個 crate 各自為同一組 trait 與型別寫出不同的實作,讓程式在加入相依套件時突然衝突。這段無法編譯:
範例:
  1. use std::fmt;
  2. impl fmt::Display for Vec<i32> {
  3. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  4. write!(f, "{} 個數字", self.len())
  5. }
  6. }
  7. fn main() {
  8. println!("{}", vec![1, 2, 3]);
  9. }

輸出:
  1. error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
  2. --> main.rs:3:1
  3. |
  4. 3 | impl fmt::Display for Vec<i32> {
  5. | ^^^^^^^^^^^^^^^^^^^^^^--------
  6. | |
  7. | `Vec` is not defined in the current crate
  8. |
  9. = note: impl doesn't have any local type before any uncovered type parameters

解法是用自己的型別包住它(newtype 模式),再為這個新型別實作:
範例:
  1. use std::fmt;
  2. struct Numbers(Vec<i32>);
  3. impl fmt::Display for Numbers {
  4. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  5. let parts: Vec<String> = self.0.iter().map(|n| n.to_string()).collect();
  6. write!(f, "[{}](共 {} 個)", parts.join(" | "), self.0.len())
  7. }
  8. }
  9. fn main() {
  10. let n = Numbers(vec![1, 2, 3]);
  11. println!("{}", n);
  12. }

輸出:
  1. [1 | 2 | 3](共 3 個)

newtype 的更多用法見進階 Trait。

用 derive 自動實作常用 trait


derive Debug、Clone、PartialEq


有些 trait 的實作方式很機械:逐一處理每個欄位。這類 trait 可以用 #[derive(...)] 屬性讓編譯器自動產生實作,前提是每個欄位的型別也都實作了該 trait。
trait能力詳見
Debug{:?} 印出std::fmt
Clone.clone() 深複製std::clone
Copy指派時複製而非移動移動與複製
PartialEq、Eq==、!=std::cmp
PartialOrd、Ord<、>、排序std::cmp
Hash當 HashMap 的鍵std::hash
DefaultType::default() 預設值std::default

範例:
  1. #[derive(Debug, Clone, PartialEq)]
  2. struct Config {
  3. name: String,
  4. retries: u32,
  5. }
  6. fn main() {
  7. let a = Config { name: String::from("api"), retries: 3 };
  8. let mut b = a.clone();
  9. println!("{:?}", a);
  10. println!("相等?{}", a == b);
  11. b.retries = 5;
  12. println!("{:#?}", b);
  13. println!("相等?{}", a == b);
  14. }

輸出:
  1. Config { name: "api", retries: 3 }
  2. 相等?true
  3. Config {
  4. name: "api",
  5. retries: 5,
  6. }
  7. 相等?false

derive 排序、雜湊與預設值


PartialOrd/Ord 用 derive 產生時,依「欄位宣告的順序」逐一比較(列舉則依變體宣告的順序)。Eq 與 Ord 是更嚴格的版本,需要搭配 PartialEq 與 PartialOrd 一起 derive。Default 讓每個欄位取其型別的預設值(數字 0、空字串、false)。
範例:
  1. use std::collections::HashSet;
  2. #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
  3. enum Level {
  4. Low,
  5. Mid,
  6. High,
  7. }
  8. #[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
  9. struct Task {
  10. level: u8,
  11. title: String,
  12. done: bool,
  13. }
  14. fn main() {
  15. let mut levels = vec![Level::High, Level::Low, Level::Mid, Level::Low];
  16. levels.sort();
  17. println!("{:?}", levels);
  18. println!("Low < High?{}", Level::Low < Level::High);
  19. let seen: HashSet<Level> = levels.iter().copied().collect();
  20. println!("出現過 Mid?{},共 {} 種", seen.contains(&Level::Mid), seen.len());
  21. let t = Task::default();
  22. println!("{:?}", t);
  23. let mut tasks = vec![
  24. Task { level: 2, title: String::from("b"), done: false },
  25. Task { level: 1, title: String::from("z"), done: true },
  26. Task { level: 2, title: String::from("a"), done: false },
  27. ];
  28. tasks.sort();
  29. let order: Vec<&str> = tasks.iter().map(|t| t.title.as_str()).collect();
  30. println!("{:?}", order);
  31. }

輸出:
  1. [Low, Low, Mid, High]
  2. Low < High?true
  3. 出現過 Mid?true,共 3 種
  4. Task { level: 0, title: "", done: false }
  5. ["z", "a", "b"]

注意:f64 沒有實作 Eq、Ord、Hash(因為 NaN 不等於自己),含 f64 欄位的型別就無法 derive 這三個 trait(見浮點數)。Display 也無法 derive,必須手寫。

下一步


trait 最大的用途是寫出「接受任何實作了某 trait 的型別」的函式,見 Trait bound 與 impl Trait;要在同一個集合裡放不同型別,見 Trait 物件與 dyn。

重點整理


  • trait 定義一組方法簽名,型別用 impl Trait for Type 明確實作
  • 預設方法讓實作者只寫核心方法,其餘可沿用或覆寫
  • 呼叫 trait 方法時,trait 必須在作用域內
  • 孤兒規則:trait 或型別至少一個屬於你的 crate;不符合時用 newtype 包裝
  • #[derive] 自動實作 Debug、Clone、PartialEq、Ord、Hash、Default 等;Display 要手寫

資料來源