3 The borrow checker uses explicit lifetime annotations to determine
4 how long references should be valid. In cases where lifetimes are not
5 elided[^1], Rust requires explicit annotations to determine what the
6 lifetime of a reference should be. The syntax for explicitly annotating
7 a lifetime uses an apostrophe character as follows:
11 // `foo` has a lifetime parameter `'a`
14 Similar to [closures][anonymity], using lifetimes requires generics.
15 Additionally, this lifetime syntax indicates that the lifetime of `foo`
16 may not exceed that of `'a`. Explicit annotation of a type has the form
17 `&'a T` where `'a` has already been introduced.
19 In cases with multiple lifetimes, the syntax is similar:
23 // `foo` has lifetime parameters `'a` and `'b`
26 In this case, the lifetime of `foo` cannot exceed that of either `'a` *or* `'b`.
28 See the following example for explicit lifetime annotation in use:
30 ```rust,editable,ignore,mdbook-runnable
31 // `print_refs` takes two references to `i32` which have different
32 // lifetimes `'a` and `'b`. These two lifetimes must both be at
33 // least as long as the function `print_refs`.
34 fn print_refs<'a, 'b>(x: &'a i32, y: &'b i32) {
35 println!("x is {} and y is {}", x, y);
38 // A function which takes no arguments, but has a lifetime parameter `'a`.
39 fn failed_borrow<'a>() {
42 // ERROR: `_x` does not live long enough
43 //let y: &'a i32 = &_x;
44 // Attempting to use the lifetime `'a` as an explicit type annotation
45 // inside the function will fail because the lifetime of `&_x` is shorter
46 // than that of `y`. A short lifetime cannot be coerced into a longer one.
50 // Create variables to be borrowed below.
51 let (four, nine) = (4, 9);
53 // Borrows (`&`) of both variables are passed into the function.
54 print_refs(&four, &nine);
55 // Any input which is borrowed must outlive the borrower.
56 // In other words, the lifetime of `four` and `nine` must
57 // be longer than that of `print_refs`.
60 // `failed_borrow` contains no references to force `'a` to be
61 // longer than the lifetime of the function, but `'a` is longer.
62 // Because the lifetime is never constrained, it defaults to `'static`.
66 [^1]: [elision] implicitly annotates lifetimes and so is different.
70 [generics][generics] and [closures][closures]
72 [anonymity]: ../../fn/closures/anonymity.md
73 [closures]: ../../fn/closures.md
75 [generics]: ../../generics.md