Trait 物件與 dyn

最後更新


特徵物件(trait object)dyn Trait 讓你在執行期才決定使用哪個型別:不同型別的值可以放進同一個集合,透過共同的 trait 操作。

為什麼需要 trait 物件


泛型在編譯期就決定型別,一個 Vec<T> 裡的元素全都是同一個 T。但有時你需要一個清單同時裝圓形、方形、三角形,只要求它們「都能算面積」。這時就需要 trait 物件。

編譯不過:Vec 只能放同一種型別


即使兩個型別實作了同一個 trait,它們仍是不同的型別,不能直接放進同一個 Vec。這段無法編譯:
範例:
  1. trait Shape {
  2. fn area(&self) -> f64;
  3. }
  4. struct Circle(f64);
  5. struct Square(f64);
  6. impl Shape for Circle {
  7. fn area(&self) -> f64 { 3.14 * self.0 * self.0 }
  8. }
  9. impl Shape for Square {
  10. fn area(&self) -> f64 { self.0 * self.0 }
  11. }
  12. fn main() {
  13. let shapes = vec![Circle(1.0), Square(2.0)];
  14. println!("{}", shapes.len());
  15. }

輸出:
  1. error[E0308]: mismatched types
  2. --> main.rs:17:36
  3. |
  4. 17 | let shapes = vec![Circle(1.0), Square(2.0)];
  5. | ^^^^^^^^^^^ expected `Circle`, found `Square`

Box<dyn Trait>:裝進同一個集合


dyn Shape 代表「某個實作了 Shape 的型別,具體是誰要到執行期才知道」。因為不同型別大小不同,dyn Shape 本身沒有固定大小,必須放在指標後面,最常見的是 Box<dyn Shape>(擁有所有權,放在堆積上,見 std::boxed)。
範例:
  1. trait Shape {
  2. fn area(&self) -> f64;
  3. fn name(&self) -> String;
  4. }
  5. struct Circle(f64);
  6. struct Rect(f64, f64);
  7. impl Shape for Circle {
  8. fn area(&self) -> f64 { 3.0 * self.0 * self.0 }
  9. fn name(&self) -> String { format!("半徑 {} 的圓", self.0) }
  10. }
  11. impl Shape for Rect {
  12. fn area(&self) -> f64 { self.0 * self.1 }
  13. fn name(&self) -> String { format!("{}x{} 的矩形", self.0, self.1) }
  14. }
  15. fn main() {
  16. let shapes: Vec<Box<dyn Shape>> = vec![
  17. Box::new(Circle(1.0)),
  18. Box::new(Rect(2.0, 3.0)),
  19. Box::new(Circle(2.0)),
  20. ];
  21. let mut total = 0.0;
  22. for s in &shapes {
  23. println!("{}:{}", s.name(), s.area());
  24. total += s.area();
  25. }
  26. println!("總面積 {}", total);
  27. }

輸出:
  1. 半徑 1 的圓:3
  2. 2x3 的矩形:6
  3. 半徑 2 的圓:12
  4. 總面積 21

範例把圓周率簡化成 3,讓輸出保持整齊。

&dyn Trait:借用的 trait 物件


不需要擁有值、只想借用時,用 &dyn Trait(或可修改的 &mut dyn Trait)。函式參數寫成 &dyn Trait,就能接受任何實作了該 trait 的值的參考(見參考與借用)。
範例:
  1. use std::fmt::Display;
  2. fn print_all(items: &[&dyn Display]) {
  3. for (i, item) in items.iter().enumerate() {
  4. println!("{}. {}", i + 1, item);
  5. }
  6. }
  7. trait Counter {
  8. fn bump(&mut self);
  9. fn value(&self) -> u32;
  10. }
  11. struct Clicks(u32);
  12. impl Counter for Clicks {
  13. fn bump(&mut self) { self.0 += 1; }
  14. fn value(&self) -> u32 { self.0 }
  15. }
  16. fn bump_twice(c: &mut dyn Counter) {
  17. c.bump();
  18. c.bump();
  19. }
  20. fn main() {
  21. print_all(&[&42, &"文字", &3.5, &'字']);
  22. let mut c = Clicks(0);
  23. bump_twice(&mut c);
  24. println!("clicks = {}", c.value());
  25. }

輸出:
  1. 1. 42
  2. 2. 文字
  3. 3. 3.5
  4. 4. 字
  5. clicks = 2

靜態分派與動態分派


兩種分派方式的差別


「分派(dispatch)」是決定「呼叫的到底是哪個型別的方法」的過程。
  • 靜態分派(泛型、impl Trait):編譯器為每個型別產生一份程式碼(單態化),呼叫的是哪個函式在編譯期就確定,還能被內聯最佳化
  • 動態分派(dyn Trait):trait 物件的指標是「胖指標(fat pointer)」,包含「資料的位址」與「虛擬函式表(vtable)的位址」;呼叫方法時先查表再跳過去

下面用兩種方式寫同一個函式,並用 size_of 比較指標大小(64 位元平台的結果,見 std::mem):一般參考是 8 bytes,&dyn 多了 vtable 指標,所以是 16 bytes。
範例:
  1. use std::mem::size_of;
  2. trait Speak {
  3. fn speak(&self) -> String;
  4. }
  5. struct Dog;
  6. struct Cat;
  7. impl Speak for Dog {
  8. fn speak(&self) -> String { String::from("汪") }
  9. }
  10. impl Speak for Cat {
  11. fn speak(&self) -> String { String::from("喵") }
  12. }
  13. fn static_call<T: Speak>(x: &T) -> String {
  14. x.speak()
  15. }
  16. fn dynamic_call(x: &dyn Speak) -> String {
  17. x.speak()
  18. }
  19. fn main() {
  20. println!("{} {}", static_call(&Dog), static_call(&Cat));
  21. println!("{} {}", dynamic_call(&Dog), dynamic_call(&Cat));
  22. println!("&Dog = {} bytes", size_of::<&Dog>());
  23. println!("&dyn Speak = {} bytes", size_of::<&dyn Speak>());
  24. println!("Box<dyn Speak> = {} bytes", size_of::<Box<dyn Speak>>());
  25. }

輸出:
  1. 汪 喵
  2. 汪 喵
  3. &Dog = 8 bytes
  4. &dyn Speak = 16 bytes
  5. Box<dyn Speak> = 16 bytes

靜態分派(T: Trait/impl Trait)動態分派(dyn Trait)
型別決定時機編譯期執行期
呼叫成本直接呼叫,可內聯經 vtable 間接呼叫
程式碼大小每個型別一份只有一份
混放不同型別不行可以

實務上:預設用泛型;需要異質集合、外掛式架構,或想減少編譯產物大小時用 dyn。動態分派的成本通常很小,不必過早擔心。

回傳 Box<dyn Trait>:執行期才決定型別


-> impl Trait 只能回傳單一具體型別(見 Trait bound 與 impl Trait)。依執行期條件回傳不同型別時,就回傳 Box<dyn Trait>。
範例:
  1. trait Greeter {
  2. fn greet(&self, name: &str) -> String;
  3. }
  4. struct Formal;
  5. struct Casual;
  6. impl Greeter for Formal {
  7. fn greet(&self, name: &str) -> String { format!("您好,{} 先生/女士。", name) }
  8. }
  9. impl Greeter for Casual {
  10. fn greet(&self, name: &str) -> String { format!("嗨 {}~", name) }
  11. }
  12. fn make_greeter(style: &str) -> Box<dyn Greeter> {
  13. if style == "formal" { Box::new(Formal) } else { Box::new(Casual) }
  14. }
  15. fn main() {
  16. for style in ["formal", "casual"] {
  17. let g = make_greeter(style);
  18. println!("{}", g.greet("林"));
  19. }
  20. }

輸出:
  1. 您好,林 先生/女士。
  2. 嗨 林~

dyn 相容性(物件安全)


哪些 trait 能做成 dyn


不是每個 trait 都能寫成 dyn Trait。能做成 trait 物件的 trait 稱為「dyn 相容(dyn compatible)」,舊稱「物件安全(object safe)」。核心原因是:透過 dyn 呼叫方法時,編譯器不知道背後的具體型別,所以方法簽名裡不能出現「需要知道具體型別才能決定」的東西。常見的限制:
不相容的寫法原因
方法回傳 Self不知道 Self 多大,無法回傳
方法有泛型參數 fn f<T>(&self, t: T)vtable 無法列出無限多種 T 的版本
沒有 self 參數的關聯函式 fn new() -> Self沒有物件可以查 vtable
trait 要求 Self: Sizeddyn Trait 本身沒有固定大小

標準庫的 Clone(clone 回傳 Self)就不是 dyn 相容的,所以沒有 Box<dyn Clone>。
範例:
  1. trait Duplicate {
  2. fn duplicate(&self) -> Self;
  3. }
  4. struct Note(String);
  5. impl Duplicate for Note {
  6. fn duplicate(&self) -> Self {
  7. Note(self.0.clone())
  8. }
  9. }
  10. fn main() {
  11. let n: Box<dyn Duplicate> = Box::new(Note(String::from("a")));
  12. let _ = n;
  13. }

輸出:
  1. error[E0038]: the trait `Duplicate` is not dyn compatible
  2. --> main.rs:14:20
  3. |
  4. 14 | let n: Box<dyn Duplicate> = Box::new(Note(String::from("a")));
  5. | ^^^^^^^^^ `Duplicate` is not dyn compatible
  6. |
  7. note: for a trait to be dyn compatible it needs to allow building a vtable
  8. for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
  9. --> main.rs:2:28
  10. |
  11. 1 | trait Duplicate {
  12. | --------- this trait is not dyn compatible...
  13. 2 | fn duplicate(&self) -> Self;
  14. | ^^^^ ...because method `duplicate` references the `Self` type in its return type

上面這段無法編譯,錯誤指出 duplicate 回傳 Self,因此 Duplicate 不是 dyn 相容的。

where Self: Sized:把個別方法排除在 dyn 之外


如果 trait 大部分方法都適合動態分派,只有一兩個不適合,可以在那些方法加上 where Self: Sized。這些方法仍可在具體型別上呼叫,只是不能透過 dyn 呼叫,而 trait 本身就變成 dyn 相容。
範例:
  1. trait Duplicate {
  2. fn label(&self) -> String;
  3. fn duplicate(&self) -> Self
  4. where
  5. Self: Sized;
  6. }
  7. struct Note(String);
  8. impl Duplicate for Note {
  9. fn label(&self) -> String {
  10. format!("note:{}", self.0)
  11. }
  12. fn duplicate(&self) -> Self {
  13. Note(format!("{}-copy", self.0))
  14. }
  15. }
  16. fn main() {
  17. let n = Note(String::from("a"));
  18. let copy = n.duplicate();
  19. let items: Vec<Box<dyn Duplicate>> = vec![Box::new(n), Box::new(copy)];
  20. for it in &items {
  21. println!("{}", it.label());
  22. }
  23. }

輸出:
  1. note:a
  2. note:a-copy

向上轉型到 supertrait


如果 trait Pet 宣告了 supertrait Animal(trait Pet: Animal,見進階 Trait),Rust 1.86 起可以直接把 &dyn Pet 轉成 &dyn Animal,Box<dyn Pet> 也能轉成 Box<dyn Animal>,稱為 trait upcasting。
範例:
  1. trait Animal {
  2. fn name(&self) -> String;
  3. }
  4. trait Pet: Animal {
  5. fn owner(&self) -> String;
  6. }
  7. struct Dog;
  8. impl Animal for Dog {
  9. fn name(&self) -> String { String::from("小黑") }
  10. }
  11. impl Pet for Dog {
  12. fn owner(&self) -> String { String::from("amy") }
  13. }
  14. fn describe(a: &dyn Animal) -> String {
  15. format!("動物:{}", a.name())
  16. }
  17. fn main() {
  18. let pet: Box<dyn Pet> = Box::new(Dog);
  19. println!("{} 的寵物", pet.owner());
  20. let animal: &dyn Animal = &*pet;
  21. println!("{}", describe(animal));
  22. let boxed: Box<dyn Animal> = pet;
  23. println!("{}", boxed.name());
  24. }

輸出:
  1. amy 的寵物
  2. 動物:小黑
  3. 小黑

需要從 trait 物件取回原本的具體型別時,可以使用 dyn Any 的 downcast_ref,見 std::any。

重點整理


  • dyn Trait 讓不同型別透過共同 trait 一起使用,必須放在指標後:Box<dyn T>、&dyn T
  • 泛型是靜態分派(編譯期決定、可內聯);dyn 是動態分派(胖指標查 vtable)
  • 預設用泛型,需要異質集合或執行期決定型別時才用 dyn
  • 只有 dyn 相容的 trait 能做成 trait 物件:方法不能回傳 Self、不能有泛型參數
  • 用 where Self: Sized 把個別方法排除在 dyn 之外;Rust 1.86 起支援向上轉型到 supertrait

資料來源