Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Lifetimes Deep Dive
生命周期深入解析

What you’ll learn: What lifetimes actually describe, why they are about relationships rather than durations, and which patterns matter most in real code.
本章将学习: 生命周期真正描述的是什么、为什么它关注的是关系而不是时长,以及真实代码里最重要的几类模式。

Difficulty: 🔴 Advanced
难度: 🔴 高级

Lifetimes are often explained badly. They do not mean “how long an object exists in wall-clock time.” They describe how borrowed references relate to one another.
生命周期经常被讲歪。它不是“对象在现实时间里活多久”,而是在描述借用引用之间的关系。

A Small Example
一个小例子

#![allow(unused)]
fn main() {
fn first<'a>(left: &'a str, _right: &'a str) -> &'a str {
    left
}
}

The annotation says: the returned reference is tied to the same lifetime relation as the inputs.
这个标注表达的意思是:返回引用和输入引用处在同一组生命周期关系里。

When Lifetimes Show Up
生命周期通常在哪些地方出现

  • returning borrowed data
    返回借用数据。
  • structs that hold references
    在结构体里持有引用。
  • complex helper functions that connect multiple borrowed values
    连接多个借用值的复杂辅助函数。

What Usually Helps
什么做法通常最有帮助

  • return owned data when practical
    能返回拥有所有权的数据时就优先返回它。
  • keep borrow scopes short
    尽量把借用作用域压短。
  • avoid storing references in structs until necessary
    在真的必要之前,先别把引用塞进结构体里。

Many lifetime problems disappear when code ownership becomes clearer.
很多生命周期问题,随着代码所有权关系变清楚,也就自己消失了。