Explicit annotation
Перевірник запозичень використовує явні анотації часу життя, щоб визначити, як довго посилання мають бути дійсними. У випадках, коли часи життя не скорочуються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`.
}
Дивіться також:
узагальнені типи and замикання
-
скорочення часу життя неявно анотує часи життя і тому відрізняється. ↩