Trait bound 與 impl Trait

最後更新


特徵約束(trait bound)限定泛型參數「必須實作哪些 trait」,impl Trait 則是同一件事的簡短寫法,也能用在回傳型別。

用 trait bound 限定泛型


泛型參數 T 什麼都可以是,所以編譯器不允許你對它做任何事。加上 trait bound,就是告訴編譯器「T 一定實作了這個 trait」,於是可以呼叫那個 trait 的方法(trait 的定義見 Trait 定義與實作)。

T: Trait


寫法是在型別參數後面加冒號與 trait 名稱:<T: Summary>。函式裡就能呼叫 Summary 的方法,而呼叫者只能傳入實作了 Summary 的型別。
範例:
  1. trait Summary {
  2. fn summarize(&self) -> String;
  3. }
  4. struct Book(&'static str);
  5. struct Song(&'static str, u32);
  6. impl Summary for Book {
  7. fn summarize(&self) -> String {
  8. format!("書:{}", self.0)
  9. }
  10. }
  11. impl Summary for Song {
  12. fn summarize(&self) -> String {
  13. format!("歌:{}({} 秒)", self.0, self.1)
  14. }
  15. }
  16. fn notify<T: Summary>(item: &T) {
  17. println!("新消息!{}", item.summarize());
  18. }
  19. fn main() {
  20. notify(&Book("Rust 實戰"));
  21. notify(&Song("Ferris 之歌", 185));
  22. }

輸出:
  1. 新消息!書:Rust 實戰
  2. 新消息!歌:Ferris 之歌(185 秒)

編譯不過:傳入沒實作 trait 的型別


trait bound 是編譯期的檢查。傳入沒有實作該 trait 的型別,這段無法編譯,錯誤訊息會直接指出缺了哪個 trait、是哪個 bound 要求的:
範例:
  1. trait Summary {
  2. fn summarize(&self) -> String;
  3. }
  4. fn notify<T: Summary>(item: &T) {
  5. println!("{}", item.summarize());
  6. }
  7. struct Photo;
  8. fn main() {
  9. notify(&Photo);
  10. }

輸出:
  1. error[E0277]: the trait bound `Photo: Summary` is not satisfied
  2. --> main.rs:12:12
  3. |
  4. 12 | notify(&Photo);
  5. | ------ ^^^^^^ unsatisfied trait bound
  6. | |
  7. | required by a bound introduced by this call
  8. |
  9. help: the trait `Summary` is not implemented for `Photo`
  10. --> main.rs:9:1
  11. |
  12. 9 | struct Photo;
  13. | ^^^^^^^^^^^^

多重 bound:用 + 連接


需要型別同時具備多種能力時,用 + 串起來。下面的 T: Display + PartialOrd 表示「能用 {} 印出,也能比較大小」(見 std::fmt、std::cmp)。
範例:
  1. use std::fmt::Display;
  2. fn print_max<T: Display + PartialOrd>(a: T, b: T) {
  3. if a >= b {
  4. println!("較大的是 {}", a);
  5. } else {
  6. println!("較大的是 {}", b);
  7. }
  8. }
  9. fn main() {
  10. print_max(3, 8);
  11. print_max("pear", "apple");
  12. print_max(2.5, -1.0);
  13. }

輸出:
  1. 較大的是 8
  2. 較大的是 pear
  3. 較大的是 2.5

where 子句:讓簽名好讀


型別參數一多、bound 一長,簽名就擠成一行難以閱讀。where 子句把 bound 移到回傳型別之後,意思完全相同,只是排版不同。習慣上 bound 超過一兩個就改用 where。
範例:
  1. use std::fmt::{Debug, Display};
  2. fn report<K, V>(key: K, values: &[V]) -> String
  3. where
  4. K: Display,
  5. V: Debug + Clone,
  6. {
  7. let first = values.first().cloned();
  8. format!("{}:共 {} 筆,第一筆 {:?}", key, values.len(), first)
  9. }
  10. fn main() {
  11. println!("{}", report("分數", &[90, 85, 77]));
  12. println!("{}", report(2026, &["a", "b"]));
  13. println!("{}", report('空', &Vec::<u8>::new()));
  14. }

輸出:
  1. 分數:共 3 筆,第一筆 Some(90)
  2. 2026:共 2 筆,第一筆 Some("a")
  3. 空:共 0 筆,第一筆 None

impl Trait


參數位置的 impl Trait


fn notify(item: &impl Summary) 是 fn notify<T: Summary>(item: &T) 的簡寫,適合只用一次、不需要命名的情況。
兩者有一個差別:每個 impl Trait 參數都是各自獨立的型別。若要求兩個參數「必須是同一個型別」,就要用具名的 T。
範例:
  1. use std::fmt::Display;
  2. fn show_both(a: impl Display, b: impl Display) {
  3. println!("{} 與 {}", a, b);
  4. }
  5. fn show_same<T: Display>(a: T, b: T) {
  6. println!("{} 與 {}(同型別)", a, b);
  7. }
  8. fn main() {
  9. show_both(1, "一");
  10. show_both('x', 2.5);
  11. show_same(10, 20);
  12. show_same("左", "右");
  13. }

輸出:
  1. 1 與 一
  2. x 與 2.5
  3. 10 與 20(同型別)
  4. 左 與 右(同型別)

show_same(10, "二") 無法編譯,因為 T 不能同時是整數與 &str;show_both 則沒有這個限制。

回傳位置的 impl Trait


-> impl Trait 表示「回傳某個實作了這個 trait 的型別,但不說是哪個」。這在兩種情況特別有用:
  • 迭代器:map、filter 串起來的型別名稱又長又難寫
  • 閉包:閉包的型別根本沒有名字,只能用 impl Fn(...) 描述

呼叫者只能使用該 trait 提供的功能;實際型別由編譯器知道,仍然是靜態分派,沒有額外成本。
範例:
  1. fn even_squares(limit: u32) -> impl Iterator<Item = u32> {
  2. (1..=limit).filter(|n| n % 2 == 0).map(|n| n * n)
  3. }
  4. fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
  5. move |x| x + step
  6. }
  7. fn main() {
  8. let v: Vec<u32> = even_squares(10).collect();
  9. println!("{:?}", v);
  10. let add5 = make_adder(5);
  11. println!("{} {}", add5(1), add5(10));
  12. }

輸出:
  1. [4, 16, 36, 64, 100]
  2. 6 15

編譯不過:impl Trait 只能回傳單一型別


-> impl Trait 雖然不寫出型別,但函式的每條路徑仍必須回傳同一個具體型別。依條件回傳兩種不同型別,這段無法編譯:
範例:
  1. use std::fmt::Display;
  2. fn label(code: bool) -> impl Display {
  3. if code {
  4. 404
  5. } else {
  6. "not found"
  7. }
  8. }
  9. fn main() {
  10. println!("{}", label(true));
  11. }

輸出:
  1. error[E0308]: `if` and `else` have incompatible types
  2. --> main.rs:7:9
  3. |
  4. 4 | / if code {
  5. 5 | | 404
  6. | | --- expected because of this
  7. 6 | | } else {
  8. 7 | | "not found"
  9. | | ^^^^^^^^^^^ expected integer, found `&str`
  10. 8 | | }
  11. | |_____- `if` and `else` have incompatible types
  12. |

真的需要在執行期決定回傳哪種型別時,改回傳 Box<dyn Display>,見 Trait 物件與 dyn。

用 bound 做條件式實作


只在 T 符合條件時提供方法


bound 也能寫在 impl 上:impl<T: Display + PartialOrd> Pair<T> 裡的方法,只有當 T 符合條件時才存在。Pair<i32> 能呼叫,裝了不能比較的型別就沒有這個方法。
更進一步,可以為「所有符合條件的型別」一次實作某個 trait,稱為 blanket implementation(全面實作)。標準庫的 impl<T: Display> ToString for T 就是例子:任何能 {} 印出的型別都自動有 .to_string()。
範例:
  1. use std::fmt::Display;
  2. struct Pair<T> {
  3. a: T,
  4. b: T,
  5. }
  6. impl<T> Pair<T> {
  7. fn new(a: T, b: T) -> Self {
  8. Pair { a, b }
  9. }
  10. }
  11. impl<T: Display + PartialOrd> Pair<T> {
  12. fn largest_label(&self) -> String {
  13. if self.a >= self.b { format!("a = {}", self.a) } else { format!("b = {}", self.b) }
  14. }
  15. }
  16. trait Shout {
  17. fn shout(&self) -> String;
  18. }
  19. impl<T: Display> Shout for T {
  20. fn shout(&self) -> String {
  21. format!("{}!!", self.to_string().to_uppercase())
  22. }
  23. }
  24. fn main() {
  25. println!("{}", Pair::new(3, 7).largest_label());
  26. let _no_display = Pair::new(vec![1], vec![2]);
  27. println!("{}", "hello".shout());
  28. println!("{}", 42.shout());
  29. }

輸出:
  1. b = 7
  2. HELLO!!
  3. 42!!

Pair::new(vec![1], vec![2]) 可以建立,但 Vec 沒有實作 Display,所以它沒有 largest_label 方法。

重點整理


  • T: Trait 讓泛型函式可以使用該 trait 的方法,並在編譯期檢查呼叫者
  • 多個 bound 用 + 連接;bound 多時改用 where 子句
  • 參數位置的 impl Trait 是簡寫,每個參數各自獨立;要求同型別時用具名 T
  • 回傳位置的 impl Trait 隱藏具體型別,適合迭代器與閉包,但只能是單一型別
  • impl<T: Bound> 可做條件式實作與 blanket implementation

資料來源