生命周期注解

A reference has a lifetime, which must not “outlive” the value it refers to. This is verified by the borrow checker.

The lifetime can be implicit - this is what we have seen so far. Lifetimes can also be explicit: &'a Point, &'document str. Lifetimes start with ' and 'a is a typical default name. Read &'a Point as “a borrowed Point which is valid for at least the lifetime a”.

Lifetimes are always inferred by the compiler: you cannot assign a lifetime yourself. Explicit lifetime annotations create constraints where there is ambiguity; the compiler verifies that there is a valid solution.

当考虑向函数传递值和从函数返回值时,生命周期会变得更加复杂。

#[derive(Debug)]
struct Point(i32, i32);

fn left_most(p1: &Point, p2: &Point) -> &Point {
    if p1.0 < p2.0 {
        p1
    } else {
        p2
    }
}

fn main() {
    let p1: Point = Point(10, 10);
    let p2: Point = Point(20, 20);
    let p3 = left_most(&p1, &p2); // What is the lifetime of p3?
    println!("p3: {p3:?}");
}
This slide should take about 10 minutes.

在此示例中,编译器无法推理出 p3 的生命周期。查看函数体内部后则可放心地假定,p3 的生命周期是 p1p2 中的较短者。但与类型一样,Rust 需要对函数参数和返回值进行明确的生命周期注解。

'a 适当添加到 left_most 中:

fn left_most<'a>(p1: &'a Point, p2: &'a Point) -> &'a Point {

这表示.,“假设 p1 和 p2 的存在时间都比 'a 更长,则返回值至少在 'a 内有效”。

在一般情况下,可以省略生命周期,如下一张幻灯片中所述。