生命週期

最後更新


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

為什麼需要生命週期


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


每個參考都有一段有效期間。借用檢查器(borrow checker)會比較「參考被使用的範圍」和「值存在的範圍」,前者不能超出後者,否則就是懸垂參考(見 參考與借用)。下面這段無法編譯:
範例:
  1. fn main() {
  2. let r: &i32;
  3. {
  4. let x = 5;
  5. r = &x;
  6. }
  7. println!("r = {}", r);
  8. }

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

flowchart TB
    subgraph outer["外層作用域:r 一直用到 println!"]
        subgraph inner["內層作用域:x 只活在這裡"]
            x["let x = 5; r = &x"]
        end
        use["println!(r) ← x 已經被釋放"]
    end
  1. flowchart TB
  2. subgraph outer["外層作用域:r 一直用到 println!"]
  3. subgraph inner["內層作用域:x 只活在這裡"]
  4. x["let x = 5; r = &x"]
  5. end
  6. use["println!(r) ← x 已經被釋放"]
  7. end

把 x 移到外層,讓值活得比參考久,就能編譯:
範例:
  1. fn main() {
  2. let x = 5;
  3. let r: &i32;
  4. {
  5. r = &x;
  6. }
  7. println!("r = {}", r);
  8. }

輸出:
  1. r = 5

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

生命週期標註


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


一個函式接收兩個參考、回傳一個參考時,編譯器光看簽名無法判斷回傳值借自哪一個參數,也就不知道呼叫端要讓誰活多久。下面這段無法編譯:
範例:
  1. fn longer(a: &str, b: &str) -> &str {
  2. if a.len() >= b.len() { a } else { b }
  3. }
  4. fn main() {
  5. println!("{}", longer("apple", "fig"));
  6. }

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

依提示加上泛型生命週期參數 'a:寫在函式名後的 <'a> 宣告它,再把 &str 寫成 &'a str。生命週期名稱以單引號開頭,習慣用小寫短名,如 'a、'b。
範例:
  1. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  2. if a.len() >= b.len() { a } else { b }
  3. }
  4. fn main() {
  5. let first = String::from("apple");
  6. let second = String::from("fig");
  7. let result = longer(&first, &second);
  8. println!("比較長的是 {}", result);
  9. }

輸出:
  1. 比較長的是 apple

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

'a 取的是較短的那一段


呼叫端如果讓其中一個參數提早被釋放,又在之後使用回傳值,就違反了這個約定。下面這段無法編譯:second 在內層區塊結束時被釋放,result 卻在區塊外才使用。
範例:
  1. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  2. if a.len() >= b.len() { a } else { b }
  3. }
  4. fn main() {
  5. let first = String::from("apple");
  6. let result;
  7. {
  8. let second = String::from("watermelon");
  9. result = longer(&first, &second);
  10. }
  11. println!("比較長的是 {}", result);
  12. }

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

兩種修法:在區塊內就把結果複製成 String;或者,如果回傳值其實只會借自其中一個參數,就只替那個參數標 'a,另一個參數就不受限制。
範例:
  1. fn longer<'a>(a: &'a str, b: &'a str) -> &'a str {
  2. if a.len() >= b.len() { a } else { b }
  3. }
  4. fn first_of<'a>(a: &'a str, _b: &str) -> &'a str {
  5. a
  6. }
  7. fn main() {
  8. let first = String::from("apple");
  9. let result;
  10. let only_first;
  11. {
  12. let second = String::from("watermelon");
  13. result = longer(&first, &second).to_string();
  14. only_first = first_of(&first, &second);
  15. }
  16. println!("{} / {}", result, only_first);
  17. }

輸出:
  1. watermelon / apple

省略規則


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


如果每個參考都要標註會非常囉唆,所以編譯器內建三條省略規則(lifetime elision),套完規則就能確定所有生命週期時,可以不寫:
規則內容
1每個參考參數各自得到一個生命週期
2只有一個參考參數時,回傳的參考都用它的生命週期
3方法有 &self 或 &mut self 時,回傳的參考用 self 的生命週期

first_word(s: &str) -> &str 套規則 2;fn name(&self) -> &str 套規則 3,所以兩者都不必標註。前面的 longer 有兩個參考參數又不是方法,三條規則都無法決定回傳值,才會出現 E0106。
範例:
  1. struct Counter {
  2. name: String,
  3. hits: u32,
  4. }
  5. impl Counter {
  6. fn name(&self) -> &str {
  7. &self.name
  8. }
  9. }
  10. fn first_word(s: &str) -> &str {
  11. s.split_whitespace().next().unwrap_or("")
  12. }
  13. fn main() {
  14. let c = Counter { name: String::from("visits"), hits: 3 };
  15. println!("{} = {}", c.name(), c.hits);
  16. println!("{}", first_word("lifetime elision rules"));
  17. }

輸出:
  1. visits = 3
  2. lifetime

結構體中的參考


欄位是參考時必須標註


結構體(struct,見 結構體)的欄位如果是參考,一定要標生命週期,省略規則不適用於結構體定義。下面這段無法編譯:
範例:
  1. struct Excerpt {
  2. text: &str,
  3. }
  4. fn main() {
  5. let e = Excerpt { text: "hi" };
  6. println!("{}", e.text);
  7. }

輸出(編譯錯誤):
  1. error[E0106]: missing lifetime specifier
  2. --> main.rs:2:11
  3. |
  4. 2 | text: &str,
  5. | ^ expected named lifetime parameter
  6. |
  7. help: consider introducing a named lifetime parameter
  8. |
  9. 1 ~ struct Excerpt<'a> {
  10. 2 ~ text: &'a str,
  11. |

struct Excerpt<'a> { text: &'a str } 表示:Excerpt 的實例不能比它借用的文字活得久。impl 區塊也要寫 impl<'a> Excerpt<'a>。
範例:
  1. struct Excerpt<'a> {
  2. text: &'a str,
  3. }
  4. impl<'a> Excerpt<'a> {
  5. fn first_sentence(source: &'a str) -> Excerpt<'a> {
  6. let end = source.find('。').map(|i| i + '。'.len_utf8()).unwrap_or(source.len());
  7. Excerpt { text: &source[..end] }
  8. }
  9. fn text(&self) -> &'a str {
  10. self.text
  11. }
  12. }
  13. fn main() {
  14. let book = String::from("所有權很重要。借用也很重要。");
  15. let saved = {
  16. let e = Excerpt::first_sentence(&book);
  17. println!("長度:{} 位元組", e.text.len());
  18. e.text()
  19. };
  20. println!("摘錄:{}", saved);
  21. }

輸出:
  1. 長度:21 位元組
  2. 摘錄:所有權很重要。

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

'static


活滿整個程式的參考


'static 是特殊的生命週期,表示參考在整個程式執行期間都有效。字串字面值與 static 變數都是 &'static str,因為它們的文字直接編進執行檔裡。
範例:
  1. fn status_text(code: u16) -> &'static str {
  2. match code {
  3. 200 => "OK",
  4. 404 => "Not Found",
  5. _ => "Unknown",
  6. }
  7. }
  8. static GREETING: &str = "哈囉";
  9. fn main() {
  10. let s: &'static str = status_text(404);
  11. println!("{} / {} / {}", s, status_text(200), GREETING);
  12. }

輸出:
  1. Not Found / OK / 哈囉

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


thread::spawn 要求傳入的閉包是 'static:新執行緒可能比目前的函式活得久,所以閉包不能借用區域變數。下面這段無法編譯,閉包預設以參考捕獲 name:
範例:
  1. use std::thread;
  2. fn main() {
  3. let name = String::from("worker");
  4. let h = thread::spawn(|| {
  5. println!("{}", name);
  6. });
  7. h.join().unwrap();
  8. }

輸出(編譯錯誤):
  1. error[E0373]: closure may outlive the current function, but it borrows `name`, which is owned by the current function
  2. --> main.rs:5:27
  3. |
  4. 5 | let h = thread::spawn(|| {
  5. | ^^ may outlive borrowed value `name`
  6. 6 | println!("{}", name);
  7. | ---- `name` is borrowed here
  8. |
  9. note: function requires argument type to outlive `'static`
  10. --> main.rs:5:13
  11. |
  12. 5 | let h = thread::spawn(|| {
  13. | _____________^
  14. 6 | | println!("{}", name);
  15. 7 | | });
  16. | |______^
  17. help: to force the closure to take ownership of `name` (and any other referenced variables), use the `move` keyword
  18. |
  19. 5 | let h = thread::spawn(move || {
  20. | ++++

加上 move,把 name 的所有權移進閉包,閉包就不再借用任何區域變數。執行緒的完整說明見 執行緒。
範例:
  1. use std::thread;
  2. fn main() {
  3. let name = String::from("worker");
  4. let h = thread::spawn(move || {
  5. println!("執行緒拿到 {}", name);
  6. });
  7. h.join().unwrap();
  8. }

輸出:
  1. 執行緒拿到 worker

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

重點整理


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

資料來源