進階 Trait

最後更新


本頁介紹 trait 的進階功能:關聯型別、泛型參數預設值、運算子多載、supertrait、完全限定語法與 newtype 模式。
先備知識:Trait 定義與實作、Trait bound 與 impl Trait。

關聯型別


關聯型別:trait 裡的型別佔位


關聯型別(associated type)是 trait 內宣告的「型別佔位」:type Item;。trait 的方法可以用 Self::Item 指稱它,實作者再決定它實際是什麼。
最常見的例子是 Iterator:每個迭代器都要說明「我產生什麼型別的元素」,就是 type Item(見 std::iter)。
範例:
  1. struct Countdown(u32);
  2. impl Iterator for Countdown {
  3. type Item = u32;
  4. fn next(&mut self) -> Option<Self::Item> {
  5. if self.0 == 0 {
  6. None
  7. } else {
  8. self.0 -= 1;
  9. Some(self.0 + 1)
  10. }
  11. }
  12. }
  13. trait Storage {
  14. type Key;
  15. fn first_key(&self) -> Option<Self::Key>;
  16. }
  17. struct Shelf(Vec<&'static str>);
  18. impl Storage for Shelf {
  19. type Key = usize;
  20. fn first_key(&self) -> Option<usize> {
  21. if self.0.is_empty() { None } else { Some(0) }
  22. }
  23. }
  24. fn main() {
  25. let v: Vec<u32> = Countdown(3).collect();
  26. println!("{:?}", v);
  27. println!("{:?}", Shelf(vec!["書"]).first_key());
  28. println!("{:?}", Shelf(vec![]).first_key());
  29. }

輸出:
  1. [3, 2, 1]
  2. Some(0)
  3. None

關聯型別與泛型參數的差別


兩者都能讓 trait 涉及「某個型別」,差別在於一個型別能實作幾次:
泛型參數 trait T<X>關聯型別 type X;
同一型別可實作幾次多次(每個 X 一次)只有一次
使用時常要指定 X不必指定,由實作決定
標準庫例子From<T>、Add<Rhs>Iterator::Item、Deref::Target

Celsius 可以同時實作 From<f64> 與 From<i32>;但一個迭代器只會有一種 Item,所以 Iterator 用關聯型別,呼叫 next() 時就不必說明要哪一種。
範例:
  1. struct Celsius(f64);
  2. impl From<f64> for Celsius {
  3. fn from(v: f64) -> Self {
  4. Celsius(v)
  5. }
  6. }
  7. impl From<i32> for Celsius {
  8. fn from(v: i32) -> Self {
  9. Celsius(v as f64)
  10. }
  11. }
  12. fn main() {
  13. let a = Celsius::from(36.5);
  14. let b: Celsius = 20.into();
  15. println!("{}°C {}°C", a.0, b.0);
  16. }

輸出:
  1. 36.5°C 20°C

運算子多載


實作 Add,讓 + 可以用在自己的型別


Rust 不能發明新的運算子,但可以為自己的型別實作 std::ops 裡對應的 trait,讓既有的運算子能用:+ 對應 Add、- 對應 Sub、* 對應 Mul、-x 對應 Neg、a[i] 對應 Index。比較運算子 ==、< 則對應 std::cmp 的 PartialEq、PartialOrd。
Add 有一個關聯型別 Output,表示相加的結果是什麼型別。
範例:
  1. use std::ops::{Add, Neg};
  2. #[derive(Debug, Clone, Copy, PartialEq)]
  3. struct Vec2 {
  4. x: i32,
  5. y: i32,
  6. }
  7. impl Add for Vec2 {
  8. type Output = Vec2;
  9. fn add(self, other: Vec2) -> Vec2 {
  10. Vec2 { x: self.x + other.x, y: self.y + other.y }
  11. }
  12. }
  13. impl Neg for Vec2 {
  14. type Output = Vec2;
  15. fn neg(self) -> Vec2 {
  16. Vec2 { x: -self.x, y: -self.y }
  17. }
  18. }
  19. fn main() {
  20. let a = Vec2 { x: 1, y: 2 };
  21. let b = Vec2 { x: 10, y: 20 };
  22. println!("{:?}", a + b);
  23. println!("{:?}", -a);
  24. println!("{}", a + b == Vec2 { x: 11, y: 22 });
  25. }

輸出:
  1. Vec2 { x: 11, y: 22 }
  2. Vec2 { x: -1, y: -2 }
  3. true

泛型參數預設值:Rhs = Self


Add 的定義是 trait Add<Rhs = Self>:型別參數 Rhs(右邊運算元的型別)有預設值 Self。所以 impl Add for Vec2 等於 impl Add<Vec2> for Vec2。需要「不同型別相加」時,明確寫出 Rhs,例如向量乘以純量、公尺加公分。
自己定義 trait 時也能用這個語法:trait Scale<Factor = f64>,大多數使用者不必寫型別參數,少數需要時再指定。
範例:
  1. use std::ops::{Add, Mul};
  2. #[derive(Debug, Clone, Copy)]
  3. struct Vec2 {
  4. x: f64,
  5. y: f64,
  6. }
  7. impl Mul<f64> for Vec2 {
  8. type Output = Vec2;
  9. fn mul(self, k: f64) -> Vec2 {
  10. Vec2 { x: self.x * k, y: self.y * k }
  11. }
  12. }
  13. #[derive(Debug)]
  14. struct Meters(f64);
  15. #[derive(Debug)]
  16. struct Centimeters(f64);
  17. impl Add<Centimeters> for Meters {
  18. type Output = Meters;
  19. fn add(self, cm: Centimeters) -> Meters {
  20. Meters(self.0 + cm.0 / 100.0)
  21. }
  22. }
  23. fn main() {
  24. let v = Vec2 { x: 1.5, y: -2.0 };
  25. println!("{:?}", v * 2.0);
  26. println!("{:?}", Meters(1.0) + Centimeters(25.0));
  27. }

輸出:
  1. Vec2 { x: 3.0, y: -4.0 }
  2. Meters(1.25)

supertrait


trait A: B:要實作 A 必須先實作 B


有時一個 trait 需要用到另一個 trait 的功能。寫成 trait Outline: Display,表示「要實作 Outline,型別必須先實作 Display」。Display 稱為 Outline 的 supertrait(父特徵),Outline 的預設方法裡就能使用 {} 印出 self。
範例:
  1. use std::fmt;
  2. trait Outline: fmt::Display {
  3. fn outline(&self) -> String {
  4. let text = self.to_string();
  5. let line = "*".repeat(text.chars().count() + 4);
  6. format!("{}\n* {} *\n{}", line, text, line)
  7. }
  8. }
  9. struct Tag(&'static str);
  10. impl fmt::Display for Tag {
  11. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  12. write!(f, "#{}", self.0)
  13. }
  14. }
  15. impl Outline for Tag {}
  16. fn main() {
  17. println!("{}", Tag("rust").outline());
  18. }

輸出:
  1. *********
  2. * #rust *
  3. *********

注意:若 Tag 沒有實作 Display 就寫 impl Outline for Tag {},會出現 E0277 錯誤,指出 Tag 沒有實作 Display。

完全限定語法


同名方法:指定要呼叫哪一個


一個型別可能從不同 trait 得到同名的方法,自己也可能有同名的方法。直接寫 x.name() 時,Rust 優先呼叫型別自己的方法;要呼叫 trait 的版本,寫成 Trait::method(&x)。
範例:
  1. trait Pilot {
  2. fn title(&self) -> String;
  3. }
  4. trait Wizard {
  5. fn title(&self) -> String;
  6. }
  7. struct Human;
  8. impl Pilot for Human {
  9. fn title(&self) -> String { String::from("機長") }
  10. }
  11. impl Wizard for Human {
  12. fn title(&self) -> String { String::from("大法師") }
  13. }
  14. impl Human {
  15. fn title(&self) -> String { String::from("普通人") }
  16. }
  17. fn main() {
  18. let h = Human;
  19. println!("{}", h.title());
  20. println!("{}", Pilot::title(&h));
  21. println!("{}", Wizard::title(&h));
  22. }

輸出:
  1. 普通人
  2. 機長
  3. 大法師

<Type as Trait>::function:沒有 self 的關聯函式


沒有 self 參數的關聯函式(例如 fn kind() -> String),Trait::kind() 這種寫法無法判斷要用哪個型別的實作。這段無法編譯:
範例:
  1. trait Animal {
  2. fn kind() -> String;
  3. }
  4. struct Dog;
  5. impl Animal for Dog {
  6. fn kind() -> String { String::from("狗") }
  7. }
  8. fn main() {
  9. println!("{}", Animal::kind());
  10. }

輸出:
  1. error[E0790]: cannot call associated function on trait without specifying the corresponding `impl` type
  2. --> main.rs:12:20
  3. |
  4. 2 | fn kind() -> String;
  5. | -------------------- `Animal::kind` defined here
  6. ...
  7. 12 | println!("{}", Animal::kind());
  8. | ^^^^^^^^^^^^^^ cannot call associated function of trait

這時要用完全限定語法(fully qualified syntax)<Type as Trait>::function(),同時寫出型別與 trait。型別自己也有同名函式時,Dog::kind() 呼叫的是型別自己的版本。
範例:
  1. trait Animal {
  2. fn kind() -> String;
  3. }
  4. struct Dog;
  5. impl Dog {
  6. fn kind() -> String { String::from("小狗(Dog 自己的函式)") }
  7. }
  8. impl Animal for Dog {
  9. fn kind() -> String { String::from("犬科(Animal 的實作)") }
  10. }
  11. fn main() {
  12. println!("{}", Dog::kind());
  13. println!("{}", <Dog as Animal>::kind());
  14. }

輸出:
  1. 小狗(Dog 自己的函式)
  2. 犬科(Animal 的實作)

newtype 模式


newtype 是「只有一個欄位的元組結構體」,例如 struct Meters(f64);。它在執行期沒有成本(大小與內部的值相同),卻是一個全新的型別。

用 newtype 繞過孤兒規則


孤兒規則不允許為外部型別實作外部 trait,例如為 Vec<String> 實作 Display。用 newtype 包一層,型別就變成自己的,可以自由實作。缺點是 Vec 的方法不再能直接呼叫,要透過 .0 存取。
範例:
  1. use std::fmt;
  2. struct Tags(Vec<String>);
  3. impl fmt::Display for Tags {
  4. fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
  5. write!(f, "[{}]", self.0.join(", "))
  6. }
  7. }
  8. fn main() {
  9. let mut t = Tags(vec![String::from("rust"), String::from("trait")]);
  10. t.0.push(String::from("newtype"));
  11. println!("{}({} 個)", t, t.0.len());
  12. }

輸出:
  1. [rust, trait, newtype](3 個)

用 newtype 區分意義不同的值


公尺與秒都是 f64,混用不會被編譯器發現。各自包成 newtype 後,參數順序寫反就會編譯錯誤,讓型別系統幫你檢查單位。
範例:
  1. use std::mem::size_of;
  2. #[derive(Debug, Clone, Copy)]
  3. struct Meters(f64);
  4. #[derive(Debug, Clone, Copy)]
  5. struct Seconds(f64);
  6. fn speed(d: Meters, t: Seconds) -> f64 {
  7. d.0 / t.0
  8. }
  9. fn main() {
  10. let d = Meters(100.0);
  11. let t = Seconds(9.58);
  12. println!("{:.2} m/s", speed(d, t));
  13. println!("Meters 大小 {} bytes,f64 大小 {} bytes", size_of::<Meters>(), size_of::<f64>());
  14. }

輸出:
  1. 10.44 m/s
  2. Meters 大小 8 bytes,f64 大小 8 bytes

若寫成 speed(t, d),會得到 error[E0308]: arguments to this function are incorrect。

重點整理


  • 關聯型別 type Item; 讓實作者決定 trait 用到的型別,每個型別只能實作一次
  • 實作 std::ops 的 Add、Mul、Neg 等 trait 即可多載運算子;Rhs = Self 是泛型參數預設值
  • trait A: B 宣告 supertrait,實作 A 前必須先實作 B
  • 同名方法用 Trait::method(&x),沒有 self 的函式用 <Type as Trait>::f()
  • newtype 繞過孤兒規則、區分意義不同的值,且沒有執行期成本

資料來源