显式标注

借用检查器使用显式的生命周期标注来确定引用的有效期。在生命周期没有被省略的情况下1,Rust 要求显式标注以确定引用的生命周期。用于显式标注生命周期的语法使用撇号字符,如下所示:

foo<'a>
// `foo` has a lifetime parameter `'a`

类似于 闭包,使用生命周期需要泛型。此外,此生命周期语法表明 foo 的生命周期不能超过 'a。类型的显式标注形式为 &'a T,其中 'a 已经提前被引入。

在具有多个生命周期的情况下,语法类似:

foo<'a, 'b>
// `foo` has lifetime parameters `'a` and `'b`

在这种情况下,foo 的生命周期不能超过 'a 'b

有关显式生命周期标注的用法,请参见以下示例:

// `print_refs` takes two references to `i32` which have different
// lifetimes `'a` and `'b`. These two lifetimes must both be at
// least as long as the function `print_refs`.
fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
    println!("x is {} and y is {}", x, y);
}

// A function which takes no arguments, but has a lifetime parameter `'a`.
fn failed_borrow<'a>() {
    let _x = 12;

    // ERROR: `_x` does not live long enough
    let _y: &'a i32 = &_x;
    // Attempting to use the lifetime `'a` as an explicit type annotation 
    // inside the function will fail because the lifetime of `&_x` is shorter
    // than that of `_y`. A short lifetime cannot be coerced into a longer one.
}

fn main() {
    // Create variables to be borrowed below.
    let (four, nine) = (4, 9);
    
    // Borrows (`&`) of both variables are passed into the function.
    print_refs(&four, &nine);
    // Any input which is borrowed must outlive the borrower. 
    // In other words, the lifetime of `four` and `nine` must 
    // be longer than that of `print_refs`.
    
    failed_borrow();
    // `failed_borrow` contains no references to force `'a` to be 
    // longer than the lifetime of the function, but `'a` is longer.
    // Because the lifetime is never constrained, it defaults to `'static`.
}
1

省略 会隐式地标注生命周期,因此有所不同。

另请参阅:

泛型闭包