4. 生命周期初识

  • 理解为什么需要生命周期。
  • 掌握生命周期标注的基本语法。
  • 了解函数和结构体中的生命周期。
  • 认识 'static 和生命周期省略规则。

生命周期(lifetime)是 Rust 借用检查器用来保证引用始终有效的机制。每个引用都有一个生命周期,表示它指向的数据在多长时间内有效。

大部分情况下,编译器可以自动推断生命周期,不需要显式写出。但在某些复杂场景下,我们需要手动标注。

考虑一个返回两个字符串中较长者的函数:

snippet.rust
fn longest(x: &str, y: &str) -> &str {
    if x.len() > y.len() {
        x
    } else {
        y
    }
}

编译会报错:

snippet.text
error[E0106]: missing lifetime specifier

为什么?因为编译器无法确定返回的引用是来自 x 还是 y,也就无法确定它的生命周期。如果返回的引用比 x 或 y 活得更久,就会出现悬垂引用。

生命周期标注使用撇号 ' 开头,例如 'a、'b。它们不改变引用的实际生命周期,只是告诉编译器多个引用之间的关系。

snippet.rust
fn longest<'a>(x: &'a str, y: &'a str) -> &'a str {
    if x.len() > y.len() {
        x
    } else {
        y }
}

含义:参数 x 和 y 都至少活得和生命周期 'a 一样长,返回值也活得和 'a 一样长。

生命周期标注描述的是约束关系,而不是具体的存活时间。

## 4.4 使用示例

snippet.rust
fn main() {
    let string1 = String::from("abcd");
    let string2 = "xyz";
 
    let result = longest(string1.as_str(), string2);
    println!("The longest string is {}", result);
}

如果换成:

snippet.rust
fn main() {
    let string1 = String::from("long string is long");
 
    {
        let string2 = String::from("xyz");
        let result = longest(string1.as_str(), string2.as_str());
        println!("The longest string is {}", result);
    }
}

这段代码可以通过,因为 result 的生命周期与 string2 一致,而 string2 在内部作用域结束时才失效。

但如果返回值被外部使用,而 string2 已经失效:

snippet.rust
fn main() {
    let string1 = String::from("long string is long");
    let result;
 
    {
        let string2 = String::from("xyz");
        result = longest(string1.as_str(), string2.as_str());
    } // string2 在这里失效,result 不能继续使用 println!("The longest string is {}", result); // 错误
}

'static 表示整个程序运行期间都有效。字符串字面量就是 'static:

snippet.rust
let s: &'static str = "I have a static lifetime.";

所有被 Box::leak 泄漏的引用也是 'static,但通常不建议这样做。

在某些常见情况下,编译器会自动推断生命周期,这被称为生命周期省略(lifetime elision)。函数参数中省略生命周期的规则如下:

  1. 每个引用参数都有一个独立的生命周期。
  2. 如果只有一个输入生命周期,那么它会被赋给所有输出生命周期。
  3. 如果有多个输入生命周期,但其中之一是 &self 或 &mut self,则 self 的生命周期会被赋给所有输出生命周期。

因此:

snippet.rust
fn first_word(s: &str) -> &str

等价于:

snippet.rust
fn first_word<'a>(s: &'a str) -> &'a str

当结构体包含引用字段时,必须为每个引用字段

该主题尚不存在

您访问的页面并不存在。如果允许,您可以使用创建该页面按钮来创建它。

  • rust/生命周期初识.txt
  • 最后更改: 2026/08/12 23:32
  • 由 张叶安