Trait 物件與 dyn
最後更新
特徵物件(trait object)
dyn Trait 讓你在執行期才決定使用哪個型別:不同型別的值可以放進同一個集合,透過共同的 trait 操作。為什麼需要 trait 物件
泛型在編譯期就決定型別,一個
Vec<T> 裡的元素全都是同一個 T。但有時你需要一個清單同時裝圓形、方形、三角形,只要求它們「都能算面積」。這時就需要 trait 物件。編譯不過:Vec 只能放同一種型別
即使兩個型別實作了同一個 trait,它們仍是不同的型別,不能直接放進同一個
Vec。這段無法編譯:範例:
- trait Shape {
- fn area(&self) -> f64;
- }
- struct Circle(f64);
- struct Square(f64);
- impl Shape for Circle {
- fn area(&self) -> f64 { 3.14 * self.0 * self.0 }
- }
- impl Shape for Square {
- fn area(&self) -> f64 { self.0 * self.0 }
- }
- fn main() {
- let shapes = vec![Circle(1.0), Square(2.0)];
- println!("{}", shapes.len());
- }
輸出:
- error[E0308]: mismatched types
- --> main.rs:17:36
- |
- 17 | let shapes = vec![Circle(1.0), Square(2.0)];
- | ^^^^^^^^^^^ expected `Circle`, found `Square`
Box<dyn Trait>:裝進同一個集合
dyn Shape 代表「某個實作了 Shape 的型別,具體是誰要到執行期才知道」。因為不同型別大小不同,dyn Shape 本身沒有固定大小,必須放在指標後面,最常見的是 Box<dyn Shape>(擁有所有權,放在堆積上,見 std::boxed)。範例:
- trait Shape {
- fn area(&self) -> f64;
- fn name(&self) -> String;
- }
- struct Circle(f64);
- struct Rect(f64, f64);
- impl Shape for Circle {
- fn area(&self) -> f64 { 3.0 * self.0 * self.0 }
- fn name(&self) -> String { format!("半徑 {} 的圓", self.0) }
- }
- impl Shape for Rect {
- fn area(&self) -> f64 { self.0 * self.1 }
- fn name(&self) -> String { format!("{}x{} 的矩形", self.0, self.1) }
- }
- fn main() {
- let shapes: Vec<Box<dyn Shape>> = vec![
- Box::new(Circle(1.0)),
- Box::new(Rect(2.0, 3.0)),
- Box::new(Circle(2.0)),
- ];
- let mut total = 0.0;
- for s in &shapes {
- println!("{}:{}", s.name(), s.area());
- total += s.area();
- }
- println!("總面積 {}", total);
- }
輸出:
- 半徑 1 的圓:3
- 2x3 的矩形:6
- 半徑 2 的圓:12
- 總面積 21
範例把圓周率簡化成 3,讓輸出保持整齊。
&dyn Trait:借用的 trait 物件
不需要擁有值、只想借用時,用
&dyn Trait(或可修改的 &mut dyn Trait)。函式參數寫成 &dyn Trait,就能接受任何實作了該 trait 的值的參考(見參考與借用)。範例:
- use std::fmt::Display;
- fn print_all(items: &[&dyn Display]) {
- for (i, item) in items.iter().enumerate() {
- println!("{}. {}", i + 1, item);
- }
- }
- trait Counter {
- fn bump(&mut self);
- fn value(&self) -> u32;
- }
- struct Clicks(u32);
- impl Counter for Clicks {
- fn bump(&mut self) { self.0 += 1; }
- fn value(&self) -> u32 { self.0 }
- }
- fn bump_twice(c: &mut dyn Counter) {
- c.bump();
- c.bump();
- }
- fn main() {
- print_all(&[&42, &"文字", &3.5, &'字']);
- let mut c = Clicks(0);
- bump_twice(&mut c);
- println!("clicks = {}", c.value());
- }
輸出:
- 1. 42
- 2. 文字
- 3. 3.5
- 4. 字
- clicks = 2
靜態分派與動態分派
兩種分派方式的差別
「分派(dispatch)」是決定「呼叫的到底是哪個型別的方法」的過程。
- 靜態分派(泛型、
impl Trait):編譯器為每個型別產生一份程式碼(單態化),呼叫的是哪個函式在編譯期就確定,還能被內聯最佳化 - 動態分派(
dyn Trait):trait 物件的指標是「胖指標(fat pointer)」,包含「資料的位址」與「虛擬函式表(vtable)的位址」;呼叫方法時先查表再跳過去
下面用兩種方式寫同一個函式,並用
size_of 比較指標大小(64 位元平台的結果,見 std::mem):一般參考是 8 bytes,&dyn 多了 vtable 指標,所以是 16 bytes。範例:
- use std::mem::size_of;
- trait Speak {
- fn speak(&self) -> String;
- }
- struct Dog;
- struct Cat;
- impl Speak for Dog {
- fn speak(&self) -> String { String::from("汪") }
- }
- impl Speak for Cat {
- fn speak(&self) -> String { String::from("喵") }
- }
- fn static_call<T: Speak>(x: &T) -> String {
- x.speak()
- }
- fn dynamic_call(x: &dyn Speak) -> String {
- x.speak()
- }
- fn main() {
- println!("{} {}", static_call(&Dog), static_call(&Cat));
- println!("{} {}", dynamic_call(&Dog), dynamic_call(&Cat));
- println!("&Dog = {} bytes", size_of::<&Dog>());
- println!("&dyn Speak = {} bytes", size_of::<&dyn Speak>());
- println!("Box<dyn Speak> = {} bytes", size_of::<Box<dyn Speak>>());
- }
輸出:
- 汪 喵
- 汪 喵
- &Dog = 8 bytes
- &dyn Speak = 16 bytes
- 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>。範例:
- trait Greeter {
- fn greet(&self, name: &str) -> String;
- }
- struct Formal;
- struct Casual;
- impl Greeter for Formal {
- fn greet(&self, name: &str) -> String { format!("您好,{} 先生/女士。", name) }
- }
- impl Greeter for Casual {
- fn greet(&self, name: &str) -> String { format!("嗨 {}~", name) }
- }
- fn make_greeter(style: &str) -> Box<dyn Greeter> {
- if style == "formal" { Box::new(Formal) } else { Box::new(Casual) }
- }
- fn main() {
- for style in ["formal", "casual"] {
- let g = make_greeter(style);
- println!("{}", g.greet("林"));
- }
- }
輸出:
- 您好,林 先生/女士。
- 嗨 林~
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: Sized | dyn Trait 本身沒有固定大小 |
標準庫的
Clone(clone 回傳 Self)就不是 dyn 相容的,所以沒有 Box<dyn Clone>。範例:
- trait Duplicate {
- fn duplicate(&self) -> Self;
- }
- struct Note(String);
- impl Duplicate for Note {
- fn duplicate(&self) -> Self {
- Note(self.0.clone())
- }
- }
- fn main() {
- let n: Box<dyn Duplicate> = Box::new(Note(String::from("a")));
- let _ = n;
- }
輸出:
- error[E0038]: the trait `Duplicate` is not dyn compatible
- --> main.rs:14:20
- |
- 14 | let n: Box<dyn Duplicate> = Box::new(Note(String::from("a")));
- | ^^^^^^^^^ `Duplicate` is not dyn compatible
- |
- note: for a trait to be dyn compatible it needs to allow building a vtable
- for more information, visit <https://doc.rust-lang.org/reference/items/traits.html#dyn-compatibility>
- --> main.rs:2:28
- |
- 1 | trait Duplicate {
- | --------- this trait is not dyn compatible...
- 2 | fn duplicate(&self) -> Self;
- | ^^^^ ...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 相容。範例:
- trait Duplicate {
- fn label(&self) -> String;
- fn duplicate(&self) -> Self
- where
- Self: Sized;
- }
- struct Note(String);
- impl Duplicate for Note {
- fn label(&self) -> String {
- format!("note:{}", self.0)
- }
- fn duplicate(&self) -> Self {
- Note(format!("{}-copy", self.0))
- }
- }
- fn main() {
- let n = Note(String::from("a"));
- let copy = n.duplicate();
- let items: Vec<Box<dyn Duplicate>> = vec![Box::new(n), Box::new(copy)];
- for it in &items {
- println!("{}", it.label());
- }
- }
輸出:
- note:a
- 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。範例:
- trait Animal {
- fn name(&self) -> String;
- }
- trait Pet: Animal {
- fn owner(&self) -> String;
- }
- struct Dog;
- impl Animal for Dog {
- fn name(&self) -> String { String::from("小黑") }
- }
- impl Pet for Dog {
- fn owner(&self) -> String { String::from("amy") }
- }
- fn describe(a: &dyn Animal) -> String {
- format!("動物:{}", a.name())
- }
- fn main() {
- let pet: Box<dyn Pet> = Box::new(Dog);
- println!("{} 的寵物", pet.owner());
- let animal: &dyn Animal = &*pet;
- println!("{}", describe(animal));
- let boxed: Box<dyn Animal> = pet;
- println!("{}", boxed.name());
- }
輸出:
- amy 的寵物
- 動物:小黑
- 小黑
需要從 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