# Trait 定義與實作

特徵（trait）描述「一種型別能做什麼」：先定義一組方法，再讓不同型別各自實作，就能用同樣的方式操作它們。

## 什麼是 trait

trait 是一份「能力清單」。例如「能被印出摘要」「能比較大小」「能被複製」。一個型別只要實作了某個 trait，就擁有那份清單上的能力。

會其他語言的讀者可以這樣對照：trait 接近 Java／C# 的 interface、Go 的 interface，但 Rust 的實作必須明確寫出 `impl Trait for Type`，不會自動符合；而且可以替既有的型別（包括 `i32`）補上新的 trait。

### 定義 trait

用 `trait` 關鍵字，裡面列出方法的簽名，以分號結尾、不寫內容。`&self` 代表方法透過借用取得呼叫它的值（見[方法](/structs-methods)）。

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

struct Article {
    title: String,
    words: usize,
}

impl Summary for Article {
    fn summarize(&self) -> String {
        format!("《{}》約 {} 字", self.title, self.words)
    }
}

fn main() {
    let a = Article { title: String::from("Rust 入門"), words: 3200 };
    println!("{}", a.summarize());
}
```

輸出：
```text
《Rust 入門》約 3200 字
```

### 為不同型別實作同一個 trait

同一個 trait 可以由許多型別實作，每個型別給出自己的版本。只要你的 crate 定義了這個 trait，也可以替標準庫的型別（如 `i32`、`Vec<T>`）實作它。

注意：要在別的模組呼叫 trait 的方法，該 trait 必須在作用域內（`use 路徑::Summary;`），否則編譯器會說找不到方法。

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

struct Tweet {
    user: String,
    text: String,
}

enum Notice {
    Maintenance(u32),
    Release(String),
}

impl Summary for Tweet {
    fn summarize(&self) -> String {
        format!("@{}：{}", self.user, self.text)
    }
}

impl Summary for Notice {
    fn summarize(&self) -> String {
        match self {
            Notice::Maintenance(min) => format!("維護 {} 分鐘", min),
            Notice::Release(v) => format!("發布 {}", v),
        }
    }
}

impl Summary for i32 {
    fn summarize(&self) -> String {
        if *self >= 0 { format!("正數 {}", self) } else { format!("負數 {}", self) }
    }
}

fn main() {
    let t = Tweet { user: String::from("ferris"), text: String::from("你好") };
    println!("{}", t.summarize());
    println!("{}", Notice::Maintenance(30).summarize());
    println!("{}", Notice::Release(String::from("v2.0")).summarize());
    println!("{}", (-5).summarize());
}
```

輸出：
```text
@ferris：你好
維護 30 分鐘
發布 v2.0
負數 -5
```

### 預設方法

trait 裡的方法可以直接寫出內容，成為預設實作（default implementation）。實作者不寫就沿用預設，寫了就覆寫。預設方法可以呼叫同一個 trait 的其他方法，所以常見的設計是：只要求實作一兩個核心方法，其餘方法用它們組合出來。

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

    fn summarize(&self) -> String {
        format!("（{} 的文章，點擊閱讀更多）", self.author())
    }
}

struct Post {
    by: String,
}

struct News {
    by: String,
    headline: String,
}

impl Summary for Post {
    fn author(&self) -> String {
        self.by.clone()
    }
}

impl Summary for News {
    fn author(&self) -> String {
        self.by.clone()
    }

    fn summarize(&self) -> String {
        format!("{}／{}", self.headline, self.author())
    }
}

fn main() {
    let p = Post { by: String::from("amy") };
    let n = News { by: String::from("ben"), headline: String::from("新版發布") };
    println!("{}", p.summarize());
    println!("{}", n.summarize());
}
```

輸出：
```text
（amy 的文章，點擊閱讀更多）
新版發布／ben
```

### 編譯不過：漏實作必要的方法

沒有預設內容的方法是「必要方法」，`impl` 時一定要寫。漏了任何一個，這段無法編譯：

範例：
```rust
trait Shape {
    fn area(&self) -> f64;
    fn name(&self) -> String;
}

struct Square(f64);

impl Shape for Square {
    fn area(&self) -> f64 {
        self.0 * self.0
    }
}

fn main() {
    println!("{}", Square(2.0).area());
}
```

輸出：
```text
error[E0046]: not all trait items implemented, missing: `name`
 --> main.rs:8:1
  |
3 |     fn name(&self) -> String;
  |     ------------------------- `name` from trait
...
8 | impl Shape for Square {
  | ^^^^^^^^^^^^^^^^^^^^^ missing `name` in implementation
```

## 孤兒規則

### 只能在「自己擁有 trait 或型別」時實作

孤兒規則（orphan rule）：`impl Trait for Type` 只有在 **trait 或型別至少有一個是你的 crate 定義的** 時候才允許。你可以為自己的型別實作標準庫的 `Display`，也可以為 `i32` 實作自己的 `Summary`；但不能為標準庫的 `Vec<i32>` 實作標準庫的 `Display`。

這條規則確保不會有兩個 crate 各自為同一組 trait 與型別寫出不同的實作，讓程式在加入相依套件時突然衝突。這段無法編譯：

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

impl fmt::Display for Vec<i32> {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{} 個數字", self.len())
    }
}

fn main() {
    println!("{}", vec![1, 2, 3]);
}
```

輸出：
```text
error[E0117]: only traits defined in the current crate can be implemented for types defined outside of the crate
 --> main.rs:3:1
  |
3 | impl fmt::Display for Vec<i32> {
  | ^^^^^^^^^^^^^^^^^^^^^^--------
  |                       |
  |                       `Vec` is not defined in the current crate
  |
  = note: impl doesn't have any local type before any uncovered type parameters
```

解法是用自己的型別包住它（newtype 模式），再為這個新型別實作：

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

struct Numbers(Vec<i32>);

impl fmt::Display for Numbers {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        let parts: Vec<String> = self.0.iter().map(|n| n.to_string()).collect();
        write!(f, "[{}]（共 {} 個）", parts.join(" | "), self.0.len())
    }
}

fn main() {
    let n = Numbers(vec![1, 2, 3]);
    println!("{}", n);
}
```

輸出：
```text
[1 | 2 | 3]（共 3 個）
```

newtype 的更多用法見[進階 Trait](/traits-advanced)。

## 用 derive 自動實作常用 trait

### derive Debug、Clone、PartialEq

有些 trait 的實作方式很機械：逐一處理每個欄位。這類 trait 可以用 `#[derive(...)]` 屬性讓編譯器自動產生實作，前提是每個欄位的型別也都實作了該 trait。

| trait | 能力 | 詳見 |
| --- | --- | --- |
| `Debug` | `{:?}` 印出 | [std::fmt](/pkg-fmt) |
| `Clone` | `.clone()` 深複製 | [std::clone](/pkg-clone) |
| `Copy` | 指派時複製而非移動 | [移動與複製](/ownership-move-copy) |
| `PartialEq`、`Eq` | `==`、`!=` | [std::cmp](/pkg-cmp) |
| `PartialOrd`、`Ord` | `<`、`>`、排序 | [std::cmp](/pkg-cmp) |
| `Hash` | 當 `HashMap` 的鍵 | [std::hash](/pkg-hash) |
| `Default` | `Type::default()` 預設值 | [std::default](/pkg-default) |

範例：
```rust
#[derive(Debug, Clone, PartialEq)]
struct Config {
    name: String,
    retries: u32,
}

fn main() {
    let a = Config { name: String::from("api"), retries: 3 };
    let mut b = a.clone();
    println!("{:?}", a);
    println!("相等？{}", a == b);
    b.retries = 5;
    println!("{:#?}", b);
    println!("相等？{}", a == b);
}
```

輸出：
```text
Config { name: "api", retries: 3 }
相等？true
Config {
    name: "api",
    retries: 5,
}
相等？false
```

### derive 排序、雜湊與預設值

`PartialOrd`／`Ord` 用 derive 產生時，依「欄位宣告的順序」逐一比較（列舉則依變體宣告的順序）。`Eq` 與 `Ord` 是更嚴格的版本，需要搭配 `PartialEq` 與 `PartialOrd` 一起 derive。`Default` 讓每個欄位取其型別的預設值（數字 0、空字串、`false`）。

範例：
```rust
use std::collections::HashSet;

#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
enum Level {
    Low,
    Mid,
    High,
}

#[derive(Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
struct Task {
    level: u8,
    title: String,
    done: bool,
}

fn main() {
    let mut levels = vec![Level::High, Level::Low, Level::Mid, Level::Low];
    levels.sort();
    println!("{:?}", levels);
    println!("Low < High？{}", Level::Low < Level::High);

    let seen: HashSet<Level> = levels.iter().copied().collect();
    println!("出現過 Mid？{}，共 {} 種", seen.contains(&Level::Mid), seen.len());

    let t = Task::default();
    println!("{:?}", t);
    let mut tasks = vec![
        Task { level: 2, title: String::from("b"), done: false },
        Task { level: 1, title: String::from("z"), done: true },
        Task { level: 2, title: String::from("a"), done: false },
    ];
    tasks.sort();
    let order: Vec<&str> = tasks.iter().map(|t| t.title.as_str()).collect();
    println!("{:?}", order);
}
```

輸出：
```text
[Low, Low, Mid, High]
Low < High？true
出現過 Mid？true，共 3 種
Task { level: 0, title: "", done: false }
["z", "a", "b"]
```

注意：`f64` 沒有實作 `Eq`、`Ord`、`Hash`（因為 `NaN` 不等於自己），含 `f64` 欄位的型別就無法 derive 這三個 trait（見[浮點數](/types-floats)）。`Display` 也無法 derive，必須手寫。

## 下一步

trait 最大的用途是寫出「接受任何實作了某 trait 的型別」的函式，見 [Trait bound 與 impl Trait](/traits-bounds)；要在同一個集合裡放不同型別，見 [Trait 物件與 dyn](/traits-objects)。

## 重點整理

- trait 定義一組方法簽名，型別用 `impl Trait for Type` 明確實作
- 預設方法讓實作者只寫核心方法，其餘可沿用或覆寫
- 呼叫 trait 方法時，trait 必須在作用域內
- 孤兒規則：trait 或型別至少一個屬於你的 crate；不符合時用 newtype 包裝
- `#[derive]` 自動實作 `Debug`、`Clone`、`PartialEq`、`Ord`、`Hash`、`Default` 等；`Display` 要手寫

## 資料來源

- [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/)
