# 生命週期

生命週期（lifetime）是編譯器追蹤「參考在哪一段程式碼內有效」的方式；大多數時候它是自動推斷的，只有編譯器猜不出來時才需要用 `'a` 標註。

## 為什麼需要生命週期

### 參考不能比它指向的值活得久

每個參考都有一段有效期間。借用檢查器（borrow checker）會比較「參考被使用的範圍」和「值存在的範圍」，前者不能超出後者，否則就是懸垂參考（見 [參考與借用](/ownership-references)）。下面這段無法編譯：

範例：
```rust
fn main() {
    let r: &i32;
    {
        let x = 5;
        r = &x;
    }
    println!("r = {}", r);
}
```

輸出（編譯錯誤）：
```text
error[E0597]: `x` does not live long enough
 --> main.rs:5:13
  |
4 |         let x = 5;
  |             - binding `x` declared here
5 |         r = &x;
  |             ^^ borrowed value does not live long enough
6 |     }
  |     - `x` dropped here while still borrowed
7 |     println!("r = {}", r);
  |                        - borrow later used here
```

```mermaid
flowchart TB
    subgraph outer["外層作用域：r 一直用到 println!"]
        subgraph inner["內層作用域：x 只活在這裡"]
            x["let x = 5; r = &x"]
        end
        use["println!(r) ← x 已經被釋放"]
    end
```

把 `x` 移到外層，讓值活得比參考久，就能編譯：

範例：
```rust
fn main() {
    let x = 5;
    let r: &i32;
    {
        r = &x;
    }
    println!("r = {}", r);
}
```

輸出：
```text
r = 5
```

注意：生命週期標註不會延長任何值的壽命，它只是「描述」參考之間的關係，讓編譯器能檢查。

## 生命週期標註

### 回傳參考時編譯器需要知道來源

一個函式接收兩個參考、回傳一個參考時，編譯器光看簽名無法判斷回傳值借自哪一個參數，也就不知道呼叫端要讓誰活多久。下面這段無法編譯：

範例：
```rust
fn longer(a: &str, b: &str) -> &str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    println!("{}", longer("apple", "fig"));
}
```

輸出（編譯錯誤）：
```text
error[E0106]: missing lifetime specifier
 --> main.rs:1:32
  |
1 | fn longer(a: &str, b: &str) -> &str {
  |              ----     ----     ^ expected named lifetime parameter
  |
  = help: this function's return type contains a borrowed value, but the signature does not say whether it is borrowed from `a` or `b`
help: consider introducing a named lifetime parameter
  |
1 | fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  |          ++++     ++          ++          ++
```

依提示加上泛型生命週期參數 `'a`：寫在函式名後的 `<'a>` 宣告它，再把 `&str` 寫成 `&'a str`。生命週期名稱以單引號開頭，習慣用小寫短名，如 `'a`、`'b`。

範例：
```rust
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let first = String::from("apple");
    let second = String::from("fig");
    let result = longer(&first, &second);
    println!("比較長的是 {}", result);
}
```

輸出：
```text
比較長的是 apple
```

`longer<'a>(a: &'a str, b: &'a str) -> &'a str` 的意思是：回傳值的有效期間，不超過 `a` 和 `b` 中比較短的那一個。

### 'a 取的是較短的那一段

呼叫端如果讓其中一個參數提早被釋放，又在之後使用回傳值，就違反了這個約定。下面這段無法編譯：`second` 在內層區塊結束時被釋放，`result` 卻在區塊外才使用。

範例：
```rust
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn main() {
    let first = String::from("apple");
    let result;
    {
        let second = String::from("watermelon");
        result = longer(&first, &second);
    }
    println!("比較長的是 {}", result);
}
```

輸出（編譯錯誤）：
```text
error[E0597]: `second` does not live long enough
  --> main.rs:10:33
   |
 9 |         let second = String::from("watermelon");
   |             ------ binding `second` declared here
10 |         result = longer(&first, &second);
   |                                 ^^^^^^^ borrowed value does not live long enough
11 |     }
   |     - `second` dropped here while still borrowed
12 |     println!("比較長的是 {}", result);
   |                               ------ borrow later used here
```

兩種修法：在區塊內就把結果複製成 `String`；或者，如果回傳值其實只會借自其中一個參數，就只替那個參數標 `'a`，另一個參數就不受限制。

範例：
```rust
fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
    if a.len() >= b.len() { a } else { b }
}

fn first_of<'a>(a: &'a str, _b: &str) -> &'a str {
    a
}

fn main() {
    let first = String::from("apple");
    let result;
    let only_first;
    {
        let second = String::from("watermelon");
        result = longer(&first, &second).to_string();
        only_first = first_of(&first, &second);
    }
    println!("{} / {}", result, only_first);
}
```

輸出：
```text
watermelon / apple
```

## 省略規則

### 大部分函式不用寫生命週期

如果每個參考都要標註會非常囉唆，所以編譯器內建三條省略規則（lifetime elision），套完規則就能確定所有生命週期時，可以不寫：

| 規則 | 內容 |
| --- | --- |
| 1 | 每個參考參數各自得到一個生命週期 |
| 2 | 只有一個參考參數時，回傳的參考都用它的生命週期 |
| 3 | 方法有 `&self` 或 `&mut self` 時，回傳的參考用 `self` 的生命週期 |

`first_word(s: &str) -> &str` 套規則 2；`fn name(&self) -> &str` 套規則 3，所以兩者都不必標註。前面的 `longer` 有兩個參考參數又不是方法，三條規則都無法決定回傳值，才會出現 E0106。

範例：
```rust
struct Counter {
    name: String,
    hits: u32,
}

impl Counter {
    fn name(&self) -> &str {
        &self.name
    }
}

fn first_word(s: &str) -> &str {
    s.split_whitespace().next().unwrap_or("")
}

fn main() {
    let c = Counter { name: String::from("visits"), hits: 3 };
    println!("{} = {}", c.name(), c.hits);
    println!("{}", first_word("lifetime elision rules"));
}
```

輸出：
```text
visits = 3
lifetime
```

## 結構體中的參考

### 欄位是參考時必須標註

結構體（struct，見 [結構體](/structs-basics)）的欄位如果是參考，一定要標生命週期，省略規則不適用於結構體定義。下面這段無法編譯：

範例：
```rust
struct Excerpt {
    text: &str,
}

fn main() {
    let e = Excerpt { text: "hi" };
    println!("{}", e.text);
}
```

輸出（編譯錯誤）：
```text
error[E0106]: missing lifetime specifier
 --> main.rs:2:11
  |
2 |     text: &str,
  |           ^ expected named lifetime parameter
  |
help: consider introducing a named lifetime parameter
  |
1 ~ struct Excerpt<'a> {
2 ~     text: &'a str,
  |
```

`struct Excerpt<'a> { text: &'a str }` 表示：`Excerpt` 的實例不能比它借用的文字活得久。`impl` 區塊也要寫 `impl<'a> Excerpt<'a>`。

範例：
```rust
struct Excerpt<'a> {
    text: &'a str,
}

impl<'a> Excerpt<'a> {
    fn first_sentence(source: &'a str) -> Excerpt<'a> {
        let end = source.find('。').map(|i| i + '。'.len_utf8()).unwrap_or(source.len());
        Excerpt { text: &source[..end] }
    }

    fn text(&self) -> &'a str {
        self.text
    }
}

fn main() {
    let book = String::from("所有權很重要。借用也很重要。");
    let saved = {
        let e = Excerpt::first_sentence(&book);
        println!("長度：{} 位元組", e.text.len());
        e.text()
    };
    println!("摘錄：{}", saved);
}
```

輸出：
```text
長度：21 位元組
摘錄：所有權很重要。
```

回傳型別寫 `&'a str` 而不是 `&str`，代表回傳的文字借自原始的 `book`，而不是借自 `Excerpt` 本身，所以即使 `e` 先被丟棄，取出的文字仍然有效。

## 'static

### 活滿整個程式的參考

`'static` 是特殊的生命週期，表示參考在整個程式執行期間都有效。字串字面值與 `static` 變數都是 `&'static str`，因為它們的文字直接編進執行檔裡。

範例：
```rust
fn status_text(code: u16) -> &'static str {
    match code {
        200 => "OK",
        404 => "Not Found",
        _ => "Unknown",
    }
}

static GREETING: &str = "哈囉";

fn main() {
    let s: &'static str = status_text(404);
    println!("{} / {} / {}", s, status_text(200), GREETING);
}
```

輸出：
```text
Not Found / OK / 哈囉
```

### T: 'static 要求不借用區域變數

`thread::spawn` 要求傳入的閉包是 `'static`：新執行緒可能比目前的函式活得久，所以閉包不能借用區域變數。下面這段無法編譯，閉包預設以參考捕獲 `name`：

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

fn main() {
    let name = String::from("worker");
    let h = thread::spawn(|| {
        println!("{}", name);
    });
    h.join().unwrap();
}
```

輸出（編譯錯誤）：
```text
error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
 --> main.rs:5:27
  |
5 |     let h = thread::spawn(|| {
  |                           ^^ may outlive borrowed value `name`
6 |         println!("{}", name);
  |                        ---- `name` is borrowed here
  |
note: function requires argument type to outlive `'static`
 --> main.rs:5:13
  |
5 |       let h = thread::spawn(|| {
  |  _____________^
6 | |         println!("{}", name);
7 | |     });
  | |______^
help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
  |
5 |     let h = thread::spawn(move || {
  |                           ++++
```

加上 `move`，把 `name` 的所有權移進閉包，閉包就不再借用任何區域變數。執行緒的完整說明見 [執行緒](/concurrency-threads)。

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

fn main() {
    let name = String::from("worker");
    let h = thread::spawn(move || {
        println!("執行緒拿到 {}", name);
    });
    h.join().unwrap();
}
```

輸出：
```text
執行緒拿到 worker
```

注意：遇到生命週期錯誤時，不要直接把參數改成 `&'static`。那只會把錯誤推到呼叫端，因為大部分資料都不是 `'static`。通常該做的是讓擁有者活得更久，或改成擁有所有權的型別（`String` 取代 `&str`）。

## 重點整理

- 生命週期描述參考的有效期間，目的是讓編譯器拒絕懸垂參考（E0597）
- 標註 `'a` 不改變任何值的壽命，只說明輸入與輸出參考的關係
- 回傳參考卻無法從省略規則推斷來源時，會出現 E0106，需要手動標註
- 結構體欄位是參考時，一定要寫 `struct Name<'a>`
- `'static` 表示整個程式期間有效；`thread::spawn` 要求 `'static`，通常用 `move` 解決

## 資料來源

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