# Trait bound 與 impl Trait

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

## 用 trait bound 限定泛型

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

### T: Trait

寫法是在型別參數後面加冒號與 trait 名稱：`<T: Summary>`。函式裡就能呼叫 `Summary` 的方法，而呼叫者只能傳入實作了 `Summary` 的型別。

範例：
```rust
trait Summary {
    fn summarize(&self) -> String;
}

struct Book(&'static str);
struct Song(&'static str, u32);

impl Summary for Book {
    fn summarize(&self) -> String {
        format!("書：{}", self.0)
    }
}

impl Summary for Song {
    fn summarize(&self) -> String {
        format!("歌：{}（{} 秒）", self.0, self.1)
    }
}

fn notify<T: Summary>(item: &T) {
    println!("新消息！{}", item.summarize());
}

fn main() {
    notify(&Book("Rust 實戰"));
    notify(&Song("Ferris 之歌", 185));
}
```

輸出：
```text
新消息！書：Rust 實戰
新消息！歌：Ferris 之歌（185 秒）
```

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

trait bound 是編譯期的檢查。傳入沒有實作該 trait 的型別，這段無法編譯，錯誤訊息會直接指出缺了哪個 trait、是哪個 bound 要求的：

範例：
```rust
trait Summary {
    fn summarize(&self) -> String;
}

fn notify<T: Summary>(item: &T) {
    println!("{}", item.summarize());
}

struct Photo;

fn main() {
    notify(&Photo);
}
```

輸出：
```text
error[E0277]: the trait bound `Photo: Summary` is not satisfied
  --> main.rs:12:12
   |
12 |     notify(&Photo);
   |     ------ ^^^^^^ unsatisfied trait bound
   |     |
   |     required by a bound introduced by this call
   |
help: the trait `Summary` is not implemented for `Photo`
  --> main.rs:9:1
   |
 9 | struct Photo;
   | ^^^^^^^^^^^^
```

### 多重 bound：用 + 連接

需要型別同時具備多種能力時，用 `+` 串起來。下面的 `T: Display + PartialOrd` 表示「能用 `{}` 印出，也能比較大小」（見 [std::fmt](/pkg-fmt)、[std::cmp](/pkg-cmp)）。

範例：
```rust
use std::fmt::Display;

fn print_max<T: Display + PartialOrd>(a: T, b: T) {
    if a >= b {
        println!("較大的是 {}", a);
    } else {
        println!("較大的是 {}", b);
    }
}

fn main() {
    print_max(3, 8);
    print_max("pear", "apple");
    print_max(2.5, -1.0);
}
```

輸出：
```text
較大的是 8
較大的是 pear
較大的是 2.5
```

### where 子句：讓簽名好讀

型別參數一多、bound 一長，簽名就擠成一行難以閱讀。`where` 子句把 bound 移到回傳型別之後，意思完全相同，只是排版不同。習慣上 bound 超過一兩個就改用 `where`。

範例：
```rust
use std::fmt::{Debug, Display};

fn report<K, V>(key: K, values: &[V]) -> String
where
    K: Display,
    V: Debug + Clone,
{
    let first = values.first().cloned();
    format!("{}：共 {} 筆，第一筆 {:?}", key, values.len(), first)
}

fn main() {
    println!("{}", report("分數", &[90, 85, 77]));
    println!("{}", report(2026, &["a", "b"]));
    println!("{}", report('空', &Vec::<u8>::new()));
}
```

輸出：
```text
分數：共 3 筆，第一筆 Some(90)
2026：共 2 筆，第一筆 Some("a")
空：共 0 筆，第一筆 None
```

## impl Trait

### 參數位置的 impl Trait

`fn notify(item: &impl Summary)` 是 `fn notify<T: Summary>(item: &T)` 的簡寫，適合只用一次、不需要命名的情況。

兩者有一個差別：每個 `impl Trait` 參數都是**各自獨立**的型別。若要求兩個參數「必須是同一個型別」，就要用具名的 `T`。

範例：
```rust
use std::fmt::Display;

fn show_both(a: impl Display, b: impl Display) {
    println!("{} 與 {}", a, b);
}

fn show_same<T: Display>(a: T, b: T) {
    println!("{} 與 {}（同型別）", a, b);
}

fn main() {
    show_both(1, "一");
    show_both('x', 2.5);
    show_same(10, 20);
    show_same("左", "右");
}
```

輸出：
```text
1 與 一
x 與 2.5
10 與 20（同型別）
左 與 右（同型別）
```

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

### 回傳位置的 impl Trait

`-> impl Trait` 表示「回傳某個實作了這個 trait 的型別，但不說是哪個」。這在兩種情況特別有用：

- [迭代器](/iterators-basics)：`map`、`filter` 串起來的型別名稱又長又難寫
- [閉包](/closures-basics)：閉包的型別根本沒有名字，只能用 `impl Fn(...)` 描述

呼叫者只能使用該 trait 提供的功能；實際型別由編譯器知道，仍然是靜態分派，沒有額外成本。

範例：
```rust
fn even_squares(limit: u32) -> impl Iterator<Item = u32> {
    (1..=limit).filter(|n| n % 2 == 0).map(|n| n * n)
}

fn make_adder(step: i32) -> impl Fn(i32) -> i32 {
    move |x| x + step
}

fn main() {
    let v: Vec<u32> = even_squares(10).collect();
    println!("{:?}", v);

    let add5 = make_adder(5);
    println!("{} {}", add5(1), add5(10));
}
```

輸出：
```text
[4, 16, 36, 64, 100]
6 15
```

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

`-> impl Trait` 雖然不寫出型別，但函式的每條路徑仍必須回傳**同一個**具體型別。依條件回傳兩種不同型別，這段無法編譯：

範例：
```rust
use std::fmt::Display;

fn label(code: bool) -> impl Display {
    if code {
        404
    } else {
        "not found"
    }
}

fn main() {
    println!("{}", label(true));
}
```

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

真的需要在執行期決定回傳哪種型別時，改回傳 `Box<dyn Display>`，見 [Trait 物件與 dyn](/traits-objects)。

## 用 bound 做條件式實作

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

bound 也能寫在 `impl` 上：`impl<T: Display + PartialOrd> Pair<T>` 裡的方法，只有當 `T` 符合條件時才存在。`Pair<i32>` 能呼叫，裝了不能比較的型別就沒有這個方法。

更進一步，可以為「所有符合條件的型別」一次實作某個 trait，稱為 blanket implementation（全面實作）。標準庫的 `impl<T: Display> ToString for T` 就是例子：任何能 `{}` 印出的型別都自動有 `.to_string()`。

範例：
```rust
use std::fmt::Display;

struct Pair<T> {
    a: T,
    b: T,
}

impl<T> Pair<T> {
    fn new(a: T, b: T) -> Self {
        Pair { a, b }
    }
}

impl<T: Display + PartialOrd> Pair<T> {
    fn largest_label(&self) -> String {
        if self.a >= self.b { format!("a = {}", self.a) } else { format!("b = {}", self.b) }
    }
}

trait Shout {
    fn shout(&self) -> String;
}

impl<T: Display> Shout for T {
    fn shout(&self) -> String {
        format!("{}！！", self.to_string().to_uppercase())
    }
}

fn main() {
    println!("{}", Pair::new(3, 7).largest_label());
    let _no_display = Pair::new(vec![1], vec![2]);
    println!("{}", "hello".shout());
    println!("{}", 42.shout());
}
```

輸出：
```text
b = 7
HELLO！！
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

## 資料來源

- [The Rust Programming Language（章節架構參考）](https://doc.rust-lang.org/book/)
- [The Rust Reference](https://doc.rust-lang.org/reference/)
- [Rust 標準庫文件](https://doc.rust-lang.org/std/)
- [Rust 官方部落格](https://blog.rust-lang.org/)
