]> git.lizzy.rs Git - rust.git/blob - src/doc/book/lifetimes.md
Unignore u128 test for stage 0,1
[rust.git] / src / doc / book / lifetimes.md
1 % Lifetimes
2
3 This is the last of three sections presenting Rust’s ownership system. This is one of
4 Rust’s most distinct and compelling features, with which Rust developers should
5 become quite acquainted. Ownership is how Rust achieves its largest goal,
6 memory safety. There are a few distinct concepts, each with its own chapter:
7
8 * [ownership][ownership], the key concept
9 * [borrowing][borrowing], and their associated feature ‘references’
10 * lifetimes, which you’re reading now
11
12 These three chapters are related, and in order. You’ll need all three to fully
13 understand the ownership system.
14
15 [ownership]: ownership.html
16 [borrowing]: references-and-borrowing.html
17
18 # Meta
19
20 Before we get to the details, two important notes about the ownership system.
21
22 Rust has a focus on safety and speed. It accomplishes these goals through many
23 ‘zero-cost abstractions’, which means that in Rust, abstractions cost as little
24 as possible in order to make them work. The ownership system is a prime example
25 of a zero-cost abstraction. All of the analysis we’ll talk about in this guide
26 is _done at compile time_. You do not pay any run-time cost for any of these
27 features.
28
29 However, this system does have a certain cost: learning curve. Many new users
30 to Rust experience something we like to call ‘fighting with the borrow
31 checker’, where the Rust compiler refuses to compile a program that the author
32 thinks is valid. This often happens because the programmer’s mental model of
33 how ownership should work doesn’t match the actual rules that Rust implements.
34 You probably will experience similar things at first. There is good news,
35 however: more experienced Rust developers report that once they work with the
36 rules of the ownership system for a period of time, they fight the borrow
37 checker less and less.
38
39 With that in mind, let’s learn about lifetimes.
40
41 # Lifetimes
42
43 Lending out a reference to a resource that someone else owns can be
44 complicated. For example, imagine this set of operations:
45
46 1. I acquire a handle to some kind of resource.
47 2. I lend you a reference to the resource.
48 3. I decide I’m done with the resource, and deallocate it, while you still have
49   your reference.
50 4. You decide to use the resource.
51
52 Uh oh! Your reference is pointing to an invalid resource. This is called a
53 dangling pointer or ‘use after free’, when the resource is memory. A small
54 example of such a situation would be:
55
56 ```rust,compile_fail
57 let r;              // Introduce reference: `r`.
58 {
59     let i = 1;      // Introduce scoped value: `i`.
60     r = &i;         // Store reference of `i` in `r`.
61 }                   // `i` goes out of scope and is dropped.
62
63 println!("{}", r);  // `r` still refers to `i`.
64 ```
65
66 To fix this, we have to make sure that step four never happens after step
67 three. In the small example above the Rust compiler is able to report the issue
68 as it can see the lifetimes of the various values in the function.
69
70 When we have a function that takes arguments by reference the situation becomes
71 more complex. Consider the following example:
72
73 ```rust,compile_fail,E0106
74 fn skip_prefix(line: &str, prefix: &str) -> &str {
75     // ...
76 #   line
77 }
78
79 let line = "lang:en=Hello World!";
80 let lang = "en";
81
82 let v;
83 {
84     let p = format!("lang:{}=", lang);  // -+ `p` comes into scope.
85     v = skip_prefix(line, p.as_str());  //  |
86 }                                       // -+ `p` goes out of scope.
87 println!("{}", v);
88 ```
89
90 Here we have a function `skip_prefix` which takes two `&str` references
91 as parameters and returns a single `&str` reference. We call it
92 by passing in references to `line` and `p`: Two variables with different
93 lifetimes. Now the safety of the `println!`-line depends on whether the
94 reference returned by `skip_prefix` function references the still living
95 `line` or the already dropped `p` string.
96
97 Because of the above ambiguity, Rust will refuse to compile the example
98 code. To get it to compile we need to tell the compiler more about the
99 lifetimes of the references. This can be done by making the lifetimes
100 explicit in the function declaration:
101
102 ```rust
103 fn skip_prefix<'a, 'b>(line: &'a str, prefix: &'b str) -> &'a str {
104     // ...
105 #   line
106 }
107 ```
108
109 Let's examine the changes without going too deep into the syntax for now -
110 we'll get to that later. The first change was adding the `<'a, 'b>` after the
111 method name. This introduces two lifetime parameters: `'a` and `'b`. Next each
112 reference in the function signature was associated with one of the lifetime
113 parameters by adding the lifetime name after the `&`. This tells the compiler
114 how the lifetimes between different references are related.
115
116 As a result the compiler is now able to deduce that the return value of
117 `skip_prefix` has the same lifetime as the `line` parameter, which makes the `v`
118 reference safe to use even after the `p` goes out of scope in the original
119 example.
120
121 In addition to the compiler being able to validate the usage of `skip_prefix`
122 return value, it can also ensure that the implementation follows the contract
123 established by the function declaration. This is useful especially when you are
124 implementing traits that are introduced [later in the book][traits].
125
126 **Note** It's important to understand that lifetime annotations are
127 _descriptive_, not _prescriptive_. This means that how long a reference is valid
128 is determined by the code, not by the annotations. The annotations, however,
129 give information about lifetimes to the compiler that uses them to check the
130 validity of references. The compiler can do so without annotations in simple
131 cases, but needs the programmer's support in complex scenarios.
132
133 [traits]: traits.html
134
135 # Syntax
136
137 The `'a` reads ‘the lifetime a’. Technically, every reference has some lifetime
138 associated with it, but the compiler lets you elide (i.e. omit, see
139 ["Lifetime Elision"][lifetime-elision] below) them in common cases. Before we
140 get to that, though, let’s look at a short example with explicit lifetimes:
141
142 [lifetime-elision]: #lifetime-elision
143
144 ```rust,ignore
145 fn bar<'a>(...)
146 ```
147
148 We previously talked a little about [function syntax][functions], but we didn’t
149 discuss the `<>`s after a function’s name. A function can have ‘generic
150 parameters’ between the `<>`s, of which lifetimes are one kind. We’ll discuss
151 other kinds of generics [later in the book][generics], but for now, let’s
152 focus on the lifetimes aspect.
153
154 [functions]: functions.html
155 [generics]: generics.html
156
157 We use `<>` to declare our lifetimes. This says that `bar` has one lifetime,
158 `'a`. If we had two reference parameters with different lifetimes, it would
159 look like this:
160
161
162 ```rust,ignore
163 fn bar<'a, 'b>(...)
164 ```
165
166 Then in our parameter list, we use the lifetimes we’ve named:
167
168 ```rust,ignore
169 ...(x: &'a i32)
170 ```
171
172 If we wanted a `&mut` reference, we’d do this:
173
174 ```rust,ignore
175 ...(x: &'a mut i32)
176 ```
177
178 If you compare `&mut i32` to `&'a mut i32`, they’re the same, it’s that
179 the lifetime `'a` has snuck in between the `&` and the `mut i32`. We read `&mut
180 i32` as ‘a mutable reference to an `i32`’ and `&'a mut i32` as ‘a mutable
181 reference to an `i32` with the lifetime `'a`’.
182
183 # In `struct`s
184
185 You’ll also need explicit lifetimes when working with [`struct`][structs]s that
186 contain references:
187
188 ```rust
189 struct Foo<'a> {
190     x: &'a i32,
191 }
192
193 fn main() {
194     let y = &5; // This is the same as `let _y = 5; let y = &_y;`.
195     let f = Foo { x: y };
196
197     println!("{}", f.x);
198 }
199 ```
200
201 [structs]: structs.html
202
203 As you can see, `struct`s can also have lifetimes. In a similar way to functions,
204
205 ```rust
206 struct Foo<'a> {
207 # x: &'a i32,
208 # }
209 ```
210
211 declares a lifetime, and
212
213 ```rust
214 # struct Foo<'a> {
215 x: &'a i32,
216 # }
217 ```
218
219 uses it. So why do we need a lifetime here? We need to ensure that any reference
220 to a `Foo` cannot outlive the reference to an `i32` it contains.
221
222 ## `impl` blocks
223
224 Let’s implement a method on `Foo`:
225
226 ```rust
227 struct Foo<'a> {
228     x: &'a i32,
229 }
230
231 impl<'a> Foo<'a> {
232     fn x(&self) -> &'a i32 { self.x }
233 }
234
235 fn main() {
236     let y = &5; // This is the same as `let _y = 5; let y = &_y;`.
237     let f = Foo { x: y };
238
239     println!("x is: {}", f.x());
240 }
241 ```
242
243 As you can see, we need to declare a lifetime for `Foo` in the `impl` line. We repeat
244 `'a` twice, like on functions: `impl<'a>` defines a lifetime `'a`, and `Foo<'a>`
245 uses it.
246
247 ## Multiple lifetimes
248
249 If you have multiple references, you can use the same lifetime multiple times:
250
251 ```rust
252 fn x_or_y<'a>(x: &'a str, y: &'a str) -> &'a str {
253 #    x
254 # }
255 ```
256
257 This says that `x` and `y` both are alive for the same scope, and that the
258 return value is also alive for that scope. If you wanted `x` and `y` to have
259 different lifetimes, you can use multiple lifetime parameters:
260
261 ```rust
262 fn x_or_y<'a, 'b>(x: &'a str, y: &'b str) -> &'a str {
263 #    x
264 # }
265 ```
266
267 In this example, `x` and `y` have different valid scopes, but the return value
268 has the same lifetime as `x`.
269
270 ## Thinking in scopes
271
272 A way to think about lifetimes is to visualize the scope that a reference is
273 valid for. For example:
274
275 ```rust
276 fn main() {
277     let y = &5;     // -+ `y` comes into scope.
278                     //  |
279     // Stuff...     //  |
280                     //  |
281 }                   // -+ `y` goes out of scope.
282 ```
283
284 Adding in our `Foo`:
285
286 ```rust
287 struct Foo<'a> {
288     x: &'a i32,
289 }
290
291 fn main() {
292     let y = &5;           // -+ `y` comes into scope.
293     let f = Foo { x: y }; // -+ `f` comes into scope.
294                           //  |
295     // Stuff...           //  |
296                           //  |
297 }                         // -+ `f` and `y` go out of scope.
298 ```
299
300 Our `f` lives within the scope of `y`, so everything works. What if it didn’t?
301 This code won’t work:
302
303 ```rust,ignore
304 struct Foo<'a> {
305     x: &'a i32,
306 }
307
308 fn main() {
309     let x;                    // -+ `x` comes into scope.
310                               //  |
311     {                         //  |
312         let y = &5;           // ---+ `y` comes into scope.
313         let f = Foo { x: y }; // ---+ `f` comes into scope.
314         x = &f.x;             //  | | This causes an error.
315     }                         // ---+ `f` and y go out of scope.
316                               //  |
317     println!("{}", x);        //  |
318 }                             // -+ `x` goes out of scope.
319 ```
320
321 Whew! As you can see here, the scopes of `f` and `y` are smaller than the scope
322 of `x`. But when we do `x = &f.x`, we make `x` a reference to something that’s
323 about to go out of scope.
324
325 Named lifetimes are a way of giving these scopes a name. Giving something a
326 name is the first step towards being able to talk about it.
327
328 ## 'static
329
330 The lifetime named ‘static’ is a special lifetime. It signals that something
331 has the lifetime of the entire program. Most Rust programmers first come across
332 `'static` when dealing with strings:
333
334 ```rust
335 let x: &'static str = "Hello, world.";
336 ```
337
338 String literals have the type `&'static str` because the reference is always
339 alive: they are baked into the data segment of the final binary. Another
340 example are globals:
341
342 ```rust
343 static FOO: i32 = 5;
344 let x: &'static i32 = &FOO;
345 ```
346
347 This adds an `i32` to the data segment of the binary, and `x` is a reference
348 to it.
349
350 ## Lifetime Elision
351
352 Rust supports powerful local type inference in the bodies of functions but not in their item signatures. 
353 It's forbidden to allow reasoning about types based on the item signature alone. 
354 However, for ergonomic reasons, a very restricted secondary inference algorithm called 
355 “lifetime elision” does apply when judging lifetimes. Lifetime elision is concerned solely with inferring 
356 lifetime parameters using three easily memorizable and unambiguous rules. This means lifetime elision 
357 acts as a shorthand for writing an item signature, while not hiding
358 away the actual types involved as full local inference would if applied to it.
359
360 When talking about lifetime elision, we use the terms *input lifetime* and
361 *output lifetime*. An *input lifetime* is a lifetime associated with a parameter
362 of a function, and an *output lifetime* is a lifetime associated with the return
363 value of a function. For example, this function has an input lifetime:
364
365 ```rust,ignore
366 fn foo<'a>(bar: &'a str)
367 ```
368
369 This one has an output lifetime:
370
371 ```rust,ignore
372 fn foo<'a>() -> &'a str
373 ```
374
375 This one has a lifetime in both positions:
376
377 ```rust,ignore
378 fn foo<'a>(bar: &'a str) -> &'a str
379 ```
380
381 Here are the three rules:
382
383 * Each elided lifetime in a function’s arguments becomes a distinct lifetime
384   parameter.
385
386 * If there is exactly one input lifetime, elided or not, that lifetime is
387   assigned to all elided lifetimes in the return values of that function.
388
389 * If there are multiple input lifetimes, but one of them is `&self` or `&mut
390   self`, the lifetime of `self` is assigned to all elided output lifetimes.
391
392 Otherwise, it is an error to elide an output lifetime.
393
394 ### Examples
395
396 Here are some examples of functions with elided lifetimes.  We’ve paired each
397 example of an elided lifetime with its expanded form.
398
399 ```rust,ignore
400 fn print(s: &str); // elided
401 fn print<'a>(s: &'a str); // expanded
402
403 fn debug(lvl: u32, s: &str); // elided
404 fn debug<'a>(lvl: u32, s: &'a str); // expanded
405 ```
406
407 In the preceding example, `lvl` doesn’t need a lifetime because it’s not a
408 reference (`&`). Only things relating to references (such as a `struct`
409 which contains a reference) need lifetimes.
410
411 ```rust,ignore
412 fn substr(s: &str, until: u32) -> &str; // elided
413 fn substr<'a>(s: &'a str, until: u32) -> &'a str; // expanded
414
415 fn get_str() -> &str; // ILLEGAL, no inputs
416
417 fn frob(s: &str, t: &str) -> &str; // ILLEGAL, two inputs
418 fn frob<'a, 'b>(s: &'a str, t: &'b str) -> &str; // Expanded: Output lifetime is ambiguous
419
420 fn get_mut(&mut self) -> &mut T; // elided
421 fn get_mut<'a>(&'a mut self) -> &'a mut T; // expanded
422
423 fn args<T: ToCStr>(&mut self, args: &[T]) -> &mut Command; // elided
424 fn args<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded
425
426 fn new(buf: &mut [u8]) -> BufWriter; // elided
427 fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>; // expanded
428 ```