]> git.proxmox.com Git - rustc.git/blob - src/doc/book/src/ch10-03-lifetime-syntax.md
New upstream version 1.61.0+dfsg1
[rustc.git] / src / doc / book / src / ch10-03-lifetime-syntax.md
1 ## Validating References with Lifetimes
2
3 Lifetimes are another kind of generic that we’ve already been using. Rather
4 than ensuring that a type has the behavior we want, lifetimes ensure that
5 references are valid as long as we need them to be.
6
7 One detail we didn’t discuss in the [“References and
8 Borrowing”][references-and-borrowing]<!-- ignore --> section in Chapter 4 is
9 that every reference in Rust has a *lifetime*, which is the scope for which
10 that reference is valid. Most of the time, lifetimes are implicit and inferred,
11 just like most of the time, types are inferred. We only must annotate types
12 when multiple types are possible. In a similar way, we must annotate lifetimes
13 when the lifetimes of references could be related in a few different ways. Rust
14 requires us to annotate the relationships using generic lifetime parameters to
15 ensure the actual references used at runtime will definitely be valid.
16
17 Annotating lifetimes is not even a concept most other programming languages
18 have, so this is going to feel unfamiliar. Although we won’t cover lifetimes in
19 their entirety in this chapter, we’ll discuss common ways you might encounter
20 lifetime syntax so you can get comfortable with the concept.
21
22 ### Preventing Dangling References with Lifetimes
23
24 The main aim of lifetimes is to prevent *dangling references*, which cause a
25 program to reference data other than the data it’s intended to reference.
26 Consider the program in Listing 10-17, which has an outer scope and an inner
27 scope.
28
29 ```rust,ignore,does_not_compile
30 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/src/main.rs:here}}
31 ```
32
33 <span class="caption">Listing 10-17: An attempt to use a reference whose value
34 has gone out of scope</span>
35
36 > Note: The examples in Listings 10-17, 10-18, and 10-24 declare variables
37 > without giving them an initial value, so the variable name exists in the
38 > outer scope. At first glance, this might appear to be in conflict with Rust’s
39 > having no null values. However, if we try to use a variable before giving it
40 > a value, we’ll get a compile-time error, which shows that Rust indeed does
41 > not allow null values.
42
43 The outer scope declares a variable named `r` with no initial value, and the
44 inner scope declares a variable named `x` with the initial value of 5. Inside
45 the inner scope, we attempt to set the value of `r` as a reference to `x`. Then
46 the inner scope ends, and we attempt to print the value in `r`. This code won’t
47 compile because the value `r` is referring to has gone out of scope before we
48 try to use it. Here is the error message:
49
50 ```console
51 {{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-17/output.txt}}
52 ```
53
54 The variable `x` doesn’t “live long enough.” The reason is that `x` will be out
55 of scope when the inner scope ends on line 7. But `r` is still valid for the
56 outer scope; because its scope is larger, we say that it “lives longer.” If
57 Rust allowed this code to work, `r` would be referencing memory that was
58 deallocated when `x` went out of scope, and anything we tried to do with `r`
59 wouldn’t work correctly. So how does Rust determine that this code is invalid?
60 It uses a borrow checker.
61
62 ### The Borrow Checker
63
64 The Rust compiler has a *borrow checker* that compares scopes to determine
65 whether all borrows are valid. Listing 10-18 shows the same code as Listing
66 10-17 but with annotations showing the lifetimes of the variables.
67
68 ```rust,ignore,does_not_compile
69 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-18/src/main.rs:here}}
70 ```
71
72 <span class="caption">Listing 10-18: Annotations of the lifetimes of `r` and
73 `x`, named `'a` and `'b`, respectively</span>
74
75 Here, we’ve annotated the lifetime of `r` with `'a` and the lifetime of `x`
76 with `'b`. As you can see, the inner `'b` block is much smaller than the outer
77 `'a` lifetime block. At compile time, Rust compares the size of the two
78 lifetimes and sees that `r` has a lifetime of `'a` but that it refers to memory
79 with a lifetime of `'b`. The program is rejected because `'b` is shorter than
80 `'a`: the subject of the reference doesn’t live as long as the reference.
81
82 Listing 10-19 fixes the code so it doesn’t have a dangling reference and
83 compiles without any errors.
84
85 ```rust
86 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-19/src/main.rs:here}}
87 ```
88
89 <span class="caption">Listing 10-19: A valid reference because the data has a
90 longer lifetime than the reference</span>
91
92 Here, `x` has the lifetime `'b`, which in this case is larger than `'a`. This
93 means `r` can reference `x` because Rust knows that the reference in `r` will
94 always be valid while `x` is valid.
95
96 Now that you know where the lifetimes of references are and how Rust analyzes
97 lifetimes to ensure references will always be valid, let’s explore generic
98 lifetimes of parameters and return values in the context of functions.
99
100 ### Generic Lifetimes in Functions
101
102 We’ll write a function that returns the longer of two string slices. This
103 function will take two string slices and return a single string slice. After
104 we’ve implemented the `longest` function, the code in Listing 10-20 should
105 print `The longest string is abcd`.
106
107 <span class="filename">Filename: src/main.rs</span>
108
109 ```rust,ignore
110 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-20/src/main.rs}}
111 ```
112
113 <span class="caption">Listing 10-20: A `main` function that calls the `longest`
114 function to find the longer of two string slices</span>
115
116 Note that we want the function to take string slices, which are references,
117 rather than strings, because we don’t want the `longest` function to take
118 ownership of its parameters. Refer to the [“String Slices as
119 Parameters”][string-slices-as-parameters]<!-- ignore --> section in Chapter 4
120 for more discussion about why the parameters we use in Listing 10-20 are the
121 ones we want.
122
123 If we try to implement the `longest` function as shown in Listing 10-21, it
124 won’t compile.
125
126 <span class="filename">Filename: src/main.rs</span>
127
128 ```rust,ignore,does_not_compile
129 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/src/main.rs:here}}
130 ```
131
132 <span class="caption">Listing 10-21: An implementation of the `longest`
133 function that returns the longer of two string slices but does not yet
134 compile</span>
135
136 Instead, we get the following error that talks about lifetimes:
137
138 ```console
139 {{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-21/output.txt}}
140 ```
141
142 The help text reveals that the return type needs a generic lifetime parameter
143 on it because Rust can’t tell whether the reference being returned refers to
144 `x` or `y`. Actually, we don’t know either, because the `if` block in the body
145 of this function returns a reference to `x` and the `else` block returns a
146 reference to `y`!
147
148 When we’re defining this function, we don’t know the concrete values that will
149 be passed into this function, so we don’t know whether the `if` case or the
150 `else` case will execute. We also don’t know the concrete lifetimes of the
151 references that will be passed in, so we can’t look at the scopes as we did in
152 Listings 10-18 and 10-19 to determine whether the reference we return will
153 always be valid. The borrow checker can’t determine this either, because it
154 doesn’t know how the lifetimes of `x` and `y` relate to the lifetime of the
155 return value. To fix this error, we’ll add generic lifetime parameters that
156 define the relationship between the references so the borrow checker can
157 perform its analysis.
158
159 ### Lifetime Annotation Syntax
160
161 Lifetime annotations don’t change how long any of the references live. Rather,
162 they describe the relationships of the lifetimes of multiple references to each
163 other without affecting the lifetimes. Just as functions can accept any type
164 when the signature specifies a generic type parameter, functions can accept
165 references with any lifetime by specifying a generic lifetime parameter.
166
167 Lifetime annotations have a slightly unusual syntax: the names of lifetime
168 parameters must start with an apostrophe (`'`) and are usually all lowercase
169 and very short, like generic types. Most people use the name `'a` for the first
170 lifetime annotation. We place lifetime parameter annotations after the `&` of a
171 reference, using a space to separate the annotation from the reference’s type.
172
173 Here are some examples: a reference to an `i32` without a lifetime parameter, a
174 reference to an `i32` that has a lifetime parameter named `'a`, and a mutable
175 reference to an `i32` that also has the lifetime `'a`.
176
177 ```rust,ignore
178 &i32 // a reference
179 &'a i32 // a reference with an explicit lifetime
180 &'a mut i32 // a mutable reference with an explicit lifetime
181 ```
182
183 One lifetime annotation by itself doesn’t have much meaning, because the
184 annotations are meant to tell Rust how generic lifetime parameters of multiple
185 references relate to each other. For example, let’s say we have a function with
186 the parameter `first` that is a reference to an `i32` with lifetime `'a`. The
187 function also has another parameter named `second` that is another reference to
188 an `i32` that also has the lifetime `'a`. The lifetime annotations indicate
189 that the references `first` and `second` must both live as long as that generic
190 lifetime.
191
192 ### Lifetime Annotations in Function Signatures
193
194 Now let’s examine lifetime annotations in the context of the `longest`
195 function. As with generic type parameters, we need to declare generic lifetime
196 parameters inside angle brackets between the function name and the parameter
197 list. We want the signature to express the following constraint: the returned
198 reference will be valid as long as both the parameters are valid. This is the
199 relationship between lifetimes of the parameters and the return value. We’ll
200 name the lifetime `'a` and then add it to each reference, as shown in Listing
201 10-22.
202
203 <span class="filename">Filename: src/main.rs</span>
204
205 ```rust
206 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-22/src/main.rs:here}}
207 ```
208
209 <span class="caption">Listing 10-22: The `longest` function definition
210 specifying that all the references in the signature must have the same lifetime
211 `'a`</span>
212
213 This code should compile and produce the result we want when we use it with the
214 `main` function in Listing 10-20.
215
216 The function signature now tells Rust that for some lifetime `'a`, the function
217 takes two parameters, both of which are string slices that live at least as
218 long as lifetime `'a`. The function signature also tells Rust that the string
219 slice returned from the function will live at least as long as lifetime `'a`.
220 In practice, it means that the lifetime of the reference returned by the
221 `longest` function is the same as the smaller of the lifetimes of the
222 references passed in. These relationships are what we want Rust to use when
223 analyzing this code.
224
225 Remember, when we specify the lifetime parameters in this function signature,
226 we’re not changing the lifetimes of any values passed in or returned. Rather,
227 we’re specifying that the borrow checker should reject any values that don’t
228 adhere to these constraints. Note that the `longest` function doesn’t need to
229 know exactly how long `x` and `y` will live, only that some scope can be
230 substituted for `'a` that will satisfy this signature.
231
232 When annotating lifetimes in functions, the annotations go in the function
233 signature, not in the function body. The lifetime annotations become part of
234 the contract of the function, much like the types in the signature. Having
235 function signatures contain the lifetime contract means the analysis the Rust
236 compiler does can be simpler. If there’s a problem with the way a function is
237 annotated or the way it is called, the compiler errors can point to the part of
238 our code and the constraints more precisely. If, instead, the Rust compiler
239 made more inferences about what we intended the relationships of the lifetimes
240 to be, the compiler might only be able to point to a use of our code many steps
241 away from the cause of the problem.
242
243 When we pass concrete references to `longest`, the concrete lifetime that is
244 substituted for `'a` is the part of the scope of `x` that overlaps with the
245 scope of `y`. In other words, the generic lifetime `'a` will get the concrete
246 lifetime that is equal to the smaller of the lifetimes of `x` and `y`. Because
247 we’ve annotated the returned reference with the same lifetime parameter `'a`,
248 the returned reference will also be valid for the length of the smaller of the
249 lifetimes of `x` and `y`.
250
251 Let’s look at how the lifetime annotations restrict the `longest` function by
252 passing in references that have different concrete lifetimes. Listing 10-23 is
253 a straightforward example.
254
255 <span class="filename">Filename: src/main.rs</span>
256
257 ```rust
258 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-23/src/main.rs:here}}
259 ```
260
261 <span class="caption">Listing 10-23: Using the `longest` function with
262 references to `String` values that have different concrete lifetimes</span>
263
264 In this example, `string1` is valid until the end of the outer scope, `string2`
265 is valid until the end of the inner scope, and `result` references something
266 that is valid until the end of the inner scope. Run this code, and you’ll see
267 that the borrow checker approves; it will compile and print `The longest string
268 is long string is long`.
269
270 Next, let’s try an example that shows that the lifetime of the reference in
271 `result` must be the smaller lifetime of the two arguments. We’ll move the
272 declaration of the `result` variable outside the inner scope but leave the
273 assignment of the value to the `result` variable inside the scope with
274 `string2`. Then we’ll move the `println!` that uses `result` to outside the
275 inner scope, after the inner scope has ended. The code in Listing 10-24 will
276 not compile.
277
278 <span class="filename">Filename: src/main.rs</span>
279
280 ```rust,ignore,does_not_compile
281 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/src/main.rs:here}}
282 ```
283
284 <span class="caption">Listing 10-24: Attempting to use `result` after `string2`
285 has gone out of scope</span>
286
287 When we try to compile this code, we get this error:
288
289 ```console
290 {{#include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-24/output.txt}}
291 ```
292
293 The error shows that for `result` to be valid for the `println!` statement,
294 `string2` would need to be valid until the end of the outer scope. Rust knows
295 this because we annotated the lifetimes of the function parameters and return
296 values using the same lifetime parameter `'a`.
297
298 As humans, we can look at this code and see that `string1` is longer than
299 `string2` and therefore `result` will contain a reference to `string1`.
300 Because `string1` has not gone out of scope yet, a reference to `string1` will
301 still be valid for the `println!` statement. However, the compiler can’t see
302 that the reference is valid in this case. We’ve told Rust that the lifetime of
303 the reference returned by the `longest` function is the same as the smaller of
304 the lifetimes of the references passed in. Therefore, the borrow checker
305 disallows the code in Listing 10-24 as possibly having an invalid reference.
306
307 Try designing more experiments that vary the values and lifetimes of the
308 references passed in to the `longest` function and how the returned reference
309 is used. Make hypotheses about whether or not your experiments will pass the
310 borrow checker before you compile; then check to see if you’re right!
311
312 ### Thinking in Terms of Lifetimes
313
314 The way in which you need to specify lifetime parameters depends on what your
315 function is doing. For example, if we changed the implementation of the
316 `longest` function to always return the first parameter rather than the longest
317 string slice, we wouldn’t need to specify a lifetime on the `y` parameter. The
318 following code will compile:
319
320 <span class="filename">Filename: src/main.rs</span>
321
322 ```rust
323 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-08-only-one-reference-with-lifetime/src/main.rs:here}}
324 ```
325
326 We’ve specified a lifetime parameter `'a` for the parameter `x` and the return
327 type, but not for the parameter `y`, because the lifetime of `y` does not have
328 any relationship with the lifetime of `x` or the return value.
329
330 When returning a reference from a function, the lifetime parameter for the
331 return type needs to match the lifetime parameter for one of the parameters. If
332 the reference returned does *not* refer to one of the parameters, it must refer
333 to a value created within this function. However, this would be a dangling
334 reference because the value will go out of scope at the end of the function.
335 Consider this attempted implementation of the `longest` function that won’t
336 compile:
337
338 <span class="filename">Filename: src/main.rs</span>
339
340 ```rust,ignore,does_not_compile
341 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/src/main.rs:here}}
342 ```
343
344 Here, even though we’ve specified a lifetime parameter `'a` for the return
345 type, this implementation will fail to compile because the return value
346 lifetime is not related to the lifetime of the parameters at all. Here is the
347 error message we get:
348
349 ```console
350 {{#include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-09-unrelated-lifetime/output.txt}}
351 ```
352
353 The problem is that `result` goes out of scope and gets cleaned up at the end
354 of the `longest` function. We’re also trying to return a reference to `result`
355 from the function. There is no way we can specify lifetime parameters that
356 would change the dangling reference, and Rust won’t let us create a dangling
357 reference. In this case, the best fix would be to return an owned data type
358 rather than a reference so the calling function is then responsible for
359 cleaning up the value.
360
361 Ultimately, lifetime syntax is about connecting the lifetimes of various
362 parameters and return values of functions. Once they’re connected, Rust has
363 enough information to allow memory-safe operations and disallow operations that
364 would create dangling pointers or otherwise violate memory safety.
365
366 ### Lifetime Annotations in Struct Definitions
367
368 So far, the structs we've define all hold owned types. We can define structs to
369 hold references, but in that case we would need to add a lifetime annotation on
370 every reference in the struct’s definition. Listing 10-25 has a struct named
371 `ImportantExcerpt` that holds a string slice.
372
373 <span class="filename">Filename: src/main.rs</span>
374
375 ```rust
376 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-25/src/main.rs}}
377 ```
378
379 <span class="caption">Listing 10-25: A struct that holds a reference, so its
380 definition needs a lifetime annotation</span>
381
382 This struct has one field, `part`, that holds a string slice, which is a
383 reference. As with generic data types, we declare the name of the generic
384 lifetime parameter inside angle brackets after the name of the struct so we can
385 use the lifetime parameter in the body of the struct definition. This
386 annotation means an instance of `ImportantExcerpt` can’t outlive the reference
387 it holds in its `part` field.
388
389 The `main` function here creates an instance of the `ImportantExcerpt` struct
390 that holds a reference to the first sentence of the `String` owned by the
391 variable `novel`. The data in `novel` exists before the `ImportantExcerpt`
392 instance is created. In addition, `novel` doesn’t go out of scope until after
393 the `ImportantExcerpt` goes out of scope, so the reference in the
394 `ImportantExcerpt` instance is valid.
395
396 ### Lifetime Elision
397
398 You’ve learned that every reference has a lifetime and that you need to specify
399 lifetime parameters for functions or structs that use references. However, in
400 Chapter 4 we had a function in Listing 4-9, shown again in Listing 10-26, that
401 compiled without lifetime annotations.
402
403 <span class="filename">Filename: src/lib.rs</span>
404
405 ```rust
406 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/listing-10-26/src/main.rs:here}}
407 ```
408
409 <span class="caption">Listing 10-26: A function we defined in Listing 4-9 that
410 compiled without lifetime annotations, even though the parameter and return
411 type are references</span>
412
413 The reason this function compiles without lifetime annotations is historical:
414 in early versions (pre-1.0) of Rust, this code wouldn’t have compiled because
415 every reference needed an explicit lifetime. At that time, the function
416 signature would have been written like this:
417
418 ```rust,ignore
419 fn first_word<'a>(s: &'a str) -> &'a str {
420 ```
421
422 After writing a lot of Rust code, the Rust team found that Rust programmers
423 were entering the same lifetime annotations over and over in particular
424 situations. These situations were predictable and followed a few deterministic
425 patterns. The developers programmed these patterns into the compiler’s code so
426 the borrow checker could infer the lifetimes in these situations and wouldn’t
427 need explicit annotations.
428
429 This piece of Rust history is relevant because it’s possible that more
430 deterministic patterns will emerge and be added to the compiler. In the future,
431 even fewer lifetime annotations might be required.
432
433 The patterns programmed into Rust’s analysis of references are called the
434 *lifetime elision rules*. These aren’t rules for programmers to follow; they’re
435 a set of particular cases that the compiler will consider, and if your code
436 fits these cases, you don’t need to write the lifetimes explicitly.
437
438 The elision rules don’t provide full inference. If Rust deterministically
439 applies the rules but there is still ambiguity as to what lifetimes the
440 references have, the compiler won’t guess what the lifetime of the remaining
441 references should be. Instead of guessing, the compiler will give you an error
442 that you can resolve by adding the lifetime annotations.
443
444 Lifetimes on function or method parameters are called *input lifetimes*, and
445 lifetimes on return values are called *output lifetimes*.
446
447 The compiler uses three rules to figure out the lifetimes of the references
448 when there aren’t explicit annotations. The first rule applies to input
449 lifetimes, and the second and third rules apply to output lifetimes. If the
450 compiler gets to the end of the three rules and there are still references for
451 which it can’t figure out lifetimes, the compiler will stop with an error.
452 These rules apply to `fn` definitions as well as `impl` blocks.
453
454 The first rule is that the compiler assigns a lifetime parameter to each
455 parameter that’s a reference. In other words, a function with one parameter
456 gets one lifetime parameter: `fn foo<'a>(x: &'a i32)`; a function with two
457 parameters gets two separate lifetime parameters: `fn foo<'a, 'b>(x: &'a i32,
458 y: &'b i32)`; and so on.
459
460 The second rule is that, if there is exactly one input lifetime parameter, that
461 lifetime is assigned to all output lifetime parameters: `fn foo<'a>(x: &'a i32)
462 -> &'a i32`.
463
464 The third rule is that, if there are multiple input lifetime parameters, but
465 one of them is `&self` or `&mut self` because this is a method, the lifetime of
466 `self` is assigned to all output lifetime parameters. This third rule makes
467 methods much nicer to read and write because fewer symbols are necessary.
468
469 Let’s pretend we’re the compiler. We’ll apply these rules to figure out the
470 lifetimes of the references in the signature of the `first_word` function in
471 Listing 10-26. The signature starts without any lifetimes associated with the
472 references:
473
474 ```rust,ignore
475 fn first_word(s: &str) -> &str {
476 ```
477
478 Then the compiler applies the first rule, which specifies that each parameter
479 gets its own lifetime. We’ll call it `'a` as usual, so now the signature is
480 this:
481
482 ```rust,ignore
483 fn first_word<'a>(s: &'a str) -> &str {
484 ```
485
486 The second rule applies because there is exactly one input lifetime. The second
487 rule specifies that the lifetime of the one input parameter gets assigned to
488 the output lifetime, so the signature is now this:
489
490 ```rust,ignore
491 fn first_word<'a>(s: &'a str) -> &'a str {
492 ```
493
494 Now all the references in this function signature have lifetimes, and the
495 compiler can continue its analysis without needing the programmer to annotate
496 the lifetimes in this function signature.
497
498 Let’s look at another example, this time using the `longest` function that had
499 no lifetime parameters when we started working with it in Listing 10-21:
500
501 ```rust,ignore
502 fn longest(x: &str, y: &str) -> &str {
503 ```
504
505 Let’s apply the first rule: each parameter gets its own lifetime. This time we
506 have two parameters instead of one, so we have two lifetimes:
507
508 ```rust,ignore
509 fn longest<'a, 'b>(x: &'a str, y: &'b str) -> &str {
510 ```
511
512 You can see that the second rule doesn’t apply because there is more than one
513 input lifetime. The third rule doesn’t apply either, because `longest` is a
514 function rather than a method, so none of the parameters are `self`. After
515 working through all three rules, we still haven’t figured out what the return
516 type’s lifetime is. This is why we got an error trying to compile the code in
517 Listing 10-21: the compiler worked through the lifetime elision rules but still
518 couldn’t figure out all the lifetimes of the references in the signature.
519
520 Because the third rule really only applies in method signatures, we’ll look at
521 lifetimes in that context next to see why the third rule means we don’t have to
522 annotate lifetimes in method signatures very often.
523
524 ### Lifetime Annotations in Method Definitions
525
526 When we implement methods on a struct with lifetimes, we use the same syntax as
527 that of generic type parameters shown in Listing 10-11. Where we declare and
528 use the lifetime parameters depends on whether they’re related to the struct
529 fields or the method parameters and return values.
530
531 Lifetime names for struct fields always need to be declared after the `impl`
532 keyword and then used after the struct’s name, because those lifetimes are part
533 of the struct’s type.
534
535 In method signatures inside the `impl` block, references might be tied to the
536 lifetime of references in the struct’s fields, or they might be independent. In
537 addition, the lifetime elision rules often make it so that lifetime annotations
538 aren’t necessary in method signatures. Let’s look at some examples using the
539 struct named `ImportantExcerpt` that we defined in Listing 10-25.
540
541 First, we’ll use a method named `level` whose only parameter is a reference to
542 `self` and whose return value is an `i32`, which is not a reference to anything:
543
544 ```rust
545 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:1st}}
546 ```
547
548 The lifetime parameter declaration after `impl` and its use after the type name
549 are required, but we’re not required to annotate the lifetime of the reference
550 to `self` because of the first elision rule.
551
552 Here is an example where the third lifetime elision rule applies:
553
554 ```rust
555 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-10-lifetimes-on-methods/src/main.rs:3rd}}
556 ```
557
558 There are two input lifetimes, so Rust applies the first lifetime elision rule
559 and gives both `&self` and `announcement` their own lifetimes. Then, because
560 one of the parameters is `&self`, the return type gets the lifetime of `&self`,
561 and all lifetimes have been accounted for.
562
563 ### The Static Lifetime
564
565 One special lifetime we need to discuss is `'static`, which denotes that the
566 affected reference *can* live for the entire duration of the program. All
567 string literals have the `'static` lifetime, which we can annotate as follows:
568
569 ```rust
570 let s: &'static str = "I have a static lifetime.";
571 ```
572
573 The text of this string is stored directly in the program’s binary, which
574 is always available. Therefore, the lifetime of all string literals is
575 `'static`.
576
577 You might see suggestions to use the `'static` lifetime in error messages. But
578 before specifying `'static` as the lifetime for a reference, think about
579 whether the reference you have actually lives the entire lifetime of your
580 program or not, and whether you want it to. Most of the time, an error message
581 suggesting the `'static` lifetime results from attempting to create a dangling
582 reference or a mismatch of the available lifetimes. In such cases, the solution
583 is fixing those problems, not specifying the `'static` lifetime.
584
585 ## Generic Type Parameters, Trait Bounds, and Lifetimes Together
586
587 Let’s briefly look at the syntax of specifying generic type parameters, trait
588 bounds, and lifetimes all in one function!
589
590 ```rust
591 {{#rustdoc_include ../listings/ch10-generic-types-traits-and-lifetimes/no-listing-11-generics-traits-and-lifetimes/src/main.rs:here}}
592 ```
593
594 This is the `longest` function from Listing 10-22 that returns the longer of
595 two string slices. But now it has an extra parameter named `ann` of the generic
596 type `T`, which can be filled in by any type that implements the `Display`
597 trait as specified by the `where` clause. This extra parameter will be printed
598 using `{}`, which is why the `Display` trait bound is necessary. Because
599 lifetimes are a type of generic, the declarations of the lifetime parameter
600 `'a` and the generic type parameter `T` go in the same list inside the angle
601 brackets after the function name.
602
603 ## Summary
604
605 We covered a lot in this chapter! Now that you know about generic type
606 parameters, traits and trait bounds, and generic lifetime parameters, you’re
607 ready to write code without repetition that works in many different situations.
608 Generic type parameters let you apply the code to different types. Traits and
609 trait bounds ensure that even though the types are generic, they’ll have the
610 behavior the code needs. You learned how to use lifetime annotations to ensure
611 that this flexible code won’t have any dangling references. And all of this
612 analysis happens at compile time, which doesn’t affect runtime performance!
613
614 Believe it or not, there is much more to learn on the topics we discussed in
615 this chapter: Chapter 17 discusses trait objects, which are another way to use
616 traits. There are also more complex scenarios involving lifetime annotations
617 that you will only need in very advanced scenarios; for those, you should read
618 the [Rust Reference][reference]. But next, you’ll learn how to write tests in
619 Rust so you can make sure your code is working the way it should.
620
621 [references-and-borrowing]:
622 ch04-02-references-and-borrowing.html#references-and-borrowing
623 [string-slices-as-parameters]:
624 ch04-03-slices.html#string-slices-as-parameters
625 [reference]: ../reference/index.html