]> git.proxmox.com Git - rustc.git/blob - src/doc/rust-by-example/src/scope/lifetime/explicit.md
New upstream version 1.76.0+dfsg1
[rustc.git] / src / doc / rust-by-example / src / scope / lifetime / explicit.md
1 # Explicit annotation
2
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:
8
9 ```rust,ignore
10 foo<'a>
11 // `foo` has a lifetime parameter `'a`
12 ```
13
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.
18
19 In cases with multiple lifetimes, the syntax is similar:
20
21 ```rust,ignore
22 foo<'a, 'b>
23 // `foo` has lifetime parameters `'a` and `'b`
24 ```
25
26 In this case, the lifetime of `foo` cannot exceed that of either `'a` *or* `'b`.
27
28 See the following example for explicit lifetime annotation in use:
29
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);
36 }
37
38 // A function which takes no arguments, but has a lifetime parameter `'a`.
39 fn failed_borrow<'a>() {
40 let _x = 12;
41
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.
47 }
48
49 fn main() {
50 // Create variables to be borrowed below.
51 let (four, nine) = (4, 9);
52
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`.
58
59 failed_borrow();
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`.
63 }
64 ```
65
66 [^1]: [elision] implicitly annotates lifetimes and so is different.
67
68 ### See also:
69
70 [generics][generics] and [closures][closures]
71
72 [anonymity]: ../../fn/closures/anonymity.md
73 [closures]: ../../fn/closures.md
74 [elision]: elision.md
75 [generics]: ../../generics.md