# 結構體

結構體（struct）把幾個相關的值包成一個有名字的型別，每個值稱為欄位（field），是 Rust 組織資料最基本的方式。

## 定義與建立

一本書有書名、頁數、能不能借，與其用三個獨立變數或一個看不出意義的元組 `(String, u32, bool)`，不如定義一個 `Book` 型別，每個欄位都有名字。

| 寫法 | 欄位存取 | 適合 |
| --- | --- | --- |
| 一般結構體 `struct Book { title: String }` | `book.title` | 欄位多、需要名字說明意義 |
| 元組結構體 `struct Meters(f64)` | `m.0` | 欄位少、包一層讓型別不會混用 |
| 單元結構體 `struct Ready;` | 沒有欄位 | 只當標記，或用來實作特徵 |

### 定義結構體並建立實例

用 `struct 名稱 { 欄位: 型別, ... }` 定義；建立實例時每個欄位都要給值，順序可以和定義不同。用 `實例.欄位` 讀寫。型別名稱慣例用大駝峰（`UpperCamelCase`），欄位用蛇形（`snake_case`）。

範例：
```rust
struct Book {
    title: String,
    pages: u32,
    available: bool,
}

fn main() {
    let mut book = Book {
        pages: 320,
        title: String::from("Rust 實戰秘笈"),
        available: true,
    };
    book.available = false;
    println!("《{}》共 {} 頁，可借：{}", book.title, book.pages, book.available);
}
```

輸出：
```text
《Rust 實戰秘笈》共 320 頁，可借：false
```

### 整個實例要 mut 才能改欄位

注意：Rust 不能只把某個欄位標成 `mut`，可變性屬於整個綁定。下面這段無法編譯，因為 `book` 沒有 `mut`：

範例：
```rust
struct Book {
    title: String,
    pages: u32,
}

fn main() {
    let book = Book { title: String::from("草稿"), pages: 10 };
    book.pages = 12;
    println!("{} {}", book.title, book.pages);
}
```

輸出（編譯錯誤）：
```text
error[E0594]: cannot assign to `book.pages`, as `book` is not declared as mutable
 --> main.rs:8:5
  |
8 |     book.pages = 12;
  |     ^^^^^^^^^^^^^^^ cannot assign
  |
help: consider changing this to be mutable
  |
7 |     let mut book = Book { title: String::from("草稿"), pages: 10 };
  |         +++
```

照提示寫 `let mut book` 就能修改任一欄位，如上一個範例。

### 欄位初始化簡寫

變數名稱和欄位名稱相同時，可以只寫一次：`User { name, email, active: true }` 等於 `User { name: name, email: email, active: true }`。常用在建構函式裡。

範例：
```rust
struct User {
    name: String,
    email: String,
    active: bool,
}

fn new_user(name: String, email: String) -> User {
    User { name, email, active: true }
}

fn main() {
    let u = new_user(String::from("ann"), String::from("ann@example.com"));
    println!("{} <{}> active={}", u.name, u.email, u.active);
}
```

輸出：
```text
ann <ann@example.com> active=true
```

## 結構體更新語法

### 用 ..base 沿用其他欄位

只想改幾個欄位、其他都沿用現有實例時，用 `..base`，必須寫在最後。

範例：
```rust
struct Config {
    host: String,
    port: u16,
    verbose: bool,
}

fn main() {
    let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
    let debug = Config { verbose: true, ..base };
    println!("{}:{} verbose={}", debug.host, debug.port, debug.verbose);
}
```

輸出：
```text
localhost:8080 verbose=true
```

### 更新語法會移動欄位

`..base` 對每個沿用的欄位做的是「指派」，所以非 `Copy` 欄位（如 `String`）會被移動走（見 [移動、複製與 Clone](/ownership-move-copy)）。下面這段無法編譯：`base.host` 已經移到 `debug`。

範例：
```rust
struct Config {
    host: String,
    port: u16,
    verbose: bool,
}

fn main() {
    let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
    let debug = Config { verbose: true, ..base };
    println!("{} {}", base.host, debug.port);
}
```

輸出（編譯錯誤）：
```text
error[E0382]: borrow of moved value: `base.host`
  --> main.rs:10:23
   |
 9 |     let debug = Config { verbose: true, ..base };
   |                 -------------------------------- value moved here
10 |     println!("{} {}", base.host, debug.port);
   |                       ^^^^^^^^^ value borrowed here after move
   |
   = note: move occurs because `base.host` has type `String`, which does not implement the `Copy` trait
```

`port` 是 `u16`、`verbose` 是 `bool`，它們是複製過去的，所以 `base.port` 仍可使用，被移走的只有 `host`。如果之後還需要 `base`，就把非 `Copy` 的欄位明確 `.clone()`：

範例：
```rust
struct Config {
    host: String,
    port: u16,
    verbose: bool,
}

fn main() {
    let base = Config { host: String::from("localhost"), port: 8080, verbose: false };
    let debug = Config { host: base.host.clone(), verbose: true, ..base };
    println!("base  = {}:{} {}", base.host, base.port, base.verbose);
    println!("debug = {}:{} {}", debug.host, debug.port, debug.verbose);
}
```

輸出：
```text
base  = localhost:8080 false
debug = localhost:8080 true
```

## 其他形式

### 元組結構體

元組結構體（tuple struct）的欄位沒有名字，只有型別，用 `.0`、`.1` 存取，也能用模式解構。常用來包一層讓型別更明確，這種寫法稱為 newtype：`Meters` 和 `Feet` 裡面都是 `f64`，但它們是不同型別，傳錯就編譯失敗。

範例：
```rust
struct Meters(f64);
struct Feet(f64);
struct Rgb(u8, u8, u8);

fn to_meters(f: Feet) -> Meters {
    Meters(f.0 * 0.3048)
}

fn main() {
    let m = to_meters(Feet(10.0));
    let Rgb(r, g, b) = Rgb(255, 128, 0);
    println!("{:.3} 公尺", m.0);
    println!("r={} g={} b={}", r, g, b);
}
```

輸出：
```text
3.048 公尺
r=255 g=128 b=0
```

### 單元結構體

單元結構體（unit struct）完全沒有欄位，大小是 0 位元組。它本身不存資料，通常用來當作標記，或替它實作特徵（trait，見 [特徵](/traits-basics)）。

範例：
```rust
use std::mem::size_of;

#[derive(Debug, PartialEq)]
struct Ready;

fn main() {
    let a = Ready;
    let b = Ready;
    println!("{:?} == {:?}：{}", a, b, a == b);
    println!("Ready 佔 {} 位元組", size_of::<Ready>());
}
```

輸出：
```text
Ready == Ready：true
Ready 佔 0 位元組
```

## 印出結構體

### 沒有 Debug 就不能用 {:?}

結構體預設不能被 `println!` 印出。`{}` 需要 `Display`、`{:?}` 需要 `Debug`，自訂型別兩者都沒有。下面這段無法編譯：

範例：
```rust
struct Point {
    x: i32,
    y: i32,
}

fn main() {
    let p = Point { x: 1, y: 2 };
    println!("{:?}", p);
}
```

輸出（編譯錯誤）：
```text
error[E0277]: `Point` doesn't implement `Debug`
 --> main.rs:8:22
  |
8 |     println!("{:?}", p);
  |               ----   ^ `Point` cannot be formatted using `{:?}` because it doesn't implement `Debug`
  |               |
  |               required by this formatting parameter
  |
  = help: the trait `Debug` is not implemented for `Point`
help: consider annotating `Point` with `#[derive(Debug)]`
  |
1 + #[derive(Debug)]
2 | struct Point {
  |
```

### derive(Debug) 與 dbg!

在定義上方加 `#[derive(Debug)]`，編譯器會自動產生 `Debug` 實作。`{:?}` 印成一行，`{:#?}` 換行縮排，適合欄位多的結構體。`dbg!(運算式)` 會把檔名、行號、運算式與值印到 stderr，並回傳那個值，除錯很方便。格式化的細節見 [std::fmt](/pkg-fmt)。

範例：
```rust
#[derive(Debug)]
struct Point {
    x: i32,
    y: i32,
}

#[derive(Debug)]
struct Line {
    start: Point,
    end: Point,
}

fn main() {
    let line = Line { start: Point { x: 0, y: 0 }, end: Point { x: 3, y: 4 } };
    println!("{:?}", line);
    println!("{:#?}", line.end);
    let dx = dbg!(line.end.x - line.start.x);
    let dy = dbg!(line.end.y - line.start.y);
    println!("平方長度 {}", dx * dx + dy * dy);
}
```

輸出：
```text
Line { start: Point { x: 0, y: 0 }, end: Point { x: 3, y: 4 } }
Point {
    x: 3,
    y: 4,
}
[main.rs:17:14] line.end.x - line.start.x = 3
[main.rs:18:14] line.end.y - line.start.y = 4
平方長度 25
```

注意：derive 出來的 `Debug` 不算「讀取欄位」。如果某個欄位只在 `{:?}` 裡被印出，編譯器仍會警告 `field is never read`。

## 重點整理

- `struct 名稱 { 欄位: 型別 }` 定義，建立時每個欄位都要給值，用 `實例.欄位` 存取
- 可變性屬於整個實例，要改欄位就寫 `let mut`（E0594）
- 欄位初始化簡寫 `User { name, email }` 與更新語法 `..base` 讓建立實例更簡潔
- `..base` 會移動非 `Copy` 欄位，之後 `base` 的那些欄位就不能用（E0382）
- 元組結構體做 newtype、單元結構體當標記
- `#[derive(Debug)]` 後才能用 `{:?}`、`{:#?}` 與 `dbg!` 印出（否則 E0277）

## 資料來源

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