]> git.lizzy.rs Git - rust.git/blob - src/doc/trpl/ownership.md
Merge pull request #21214 from sleepynate/spacing-in-book
[rust.git] / src / doc / trpl / ownership.md
1 % The Rust Ownership Guide
2
3 This guide presents Rust's ownership system. This is one of Rust's most unique
4 and compelling features, with which Rust developers should become quite
5 acquainted. Ownership is how Rust achieves its largest goal, memory safety.
6 The ownership system has a few distinct concepts: *ownership*, *borrowing*,
7 and *lifetimes*. We'll talk about each one in turn.
8
9 # Meta
10
11 Before we get to the details, two important notes about the ownership system.
12
13 Rust has a focus on safety and speed. It accomplishes these goals through many
14 *zero-cost abstractions*, which means that in Rust, abstractions cost as little
15 as possible in order to make them work. The ownership system is a prime example
16 of a zero cost abstraction. All of the analysis we'll talk about in this guide
17 is _done at compile time_. You do not pay any run-time cost for any of these
18 features.
19
20 However, this system does have a certain cost: learning curve. Many new users
21 to Rust experience something we like to call "fighting with the borrow
22 checker," where the Rust compiler refuses to compile a program that the author
23 thinks is valid. This often happens because the programmer's mental model of
24 how ownership should work doesn't match the actual rules that Rust implements.
25 You probably will experience similar things at first. There is good news,
26 however: more experienced Rust developers report that once they work with the
27 rules of the ownership system for a period of time, they fight the borrow
28 checker less and less.
29
30 With that in mind, let's learn about ownership.
31
32 # Ownership
33
34 At its core, ownership is about *resources*. For the purposes of the vast
35 majority of this guide, we will talk about a specific resource: memory. The
36 concept generalizes to any kind of resource, like a file handle, but to make it
37 more concrete, we'll focus on memory.
38
39 When your program allocates some memory, it needs some way to deallocate that
40 memory. Imagine a function `foo` that allocates four bytes of memory, and then
41 never deallocates that memory. We call this problem *leaking* memory, because
42 each time we call `foo`, we're allocating another four bytes. Eventually, with
43 enough calls to `foo`, we will run our system out of memory. That's no good. So
44 we need some way for `foo` to deallocate those four bytes. It's also important
45 that we don't deallocate too many times, either. Without getting into the
46 details, attempting to deallocate memory multiple times can lead to problems.
47 In other words, any time some memory is allocated, we need to make sure that we
48 deallocate that memory once and only once. Too many times is bad, not enough
49 times is bad. The counts must match.
50
51 There's one other important detail with regards to allocating memory. Whenever
52 we request some amount of memory, what we are given is a handle to that memory.
53 This handle (often called a *pointer*, when we're referring to memory) is how
54 we interact with the allocated memory. As long as we have that handle, we can
55 do something with the memory. Once we're done with the handle, we're also done
56 with the memory, as we can't do anything useful without a handle to it.
57
58 Historically, systems programming languages require you to track these
59 allocations, deallocations, and handles yourself. For example, if we want some
60 memory from the heap in a language like C, we do this:
61
62 ```c
63 {
64     int *x = malloc(sizeof(int));
65
66     // we can now do stuff with our handle x
67     *x = 5;
68
69     free(x);
70 }
71 ```
72
73 The call to `malloc` allocates some memory. The call to `free` deallocates the
74 memory. There's also bookkeeping about allocating the correct amount of memory.
75
76 Rust combines these two aspects of allocating memory (and other resources) into
77 a concept called *ownership*. Whenever we request some memory, that handle we
78 receive is called the *owning handle*. Whenever that handle goes out of scope,
79 Rust knows that you cannot do anything with the memory anymore, and so
80 therefore deallocates the memory for you. Here's the equivalent example in
81 Rust:
82
83 ```rust
84 {
85     let x = Box::new(5);
86 }
87 ```
88
89 The `Box::new` function creates a `Box<T>` (specifically `Box<i32>` in this
90 case) by allocating a small segment of memory on the heap with enough space to
91 fit an `i32`. But where in the code is the box deallocated? We said before that
92 we must have a deallocation for each allocation. Rust handles this for you. It
93 knows that our handle, `x`, is the owning reference to our box. Rust knows that
94 `x` will go out of scope at the end of the block, and so it inserts a call to
95 deallocate the memory at the end of the scope. Because the compiler does this
96 for us, it's impossible to forget. We always have exactly one deallocation
97   paired with each of our allocations.
98
99 This is pretty straightforward, but what happens when we want to pass our box
100 to a function? Let's look at some code:
101
102 ```rust
103 fn main() {
104     let x = Box::new(5);
105
106     add_one(x);
107 }
108
109 fn add_one(mut num: Box<i32>) {
110     *num += 1;
111 }
112 ```
113
114 This code works, but it's not ideal. For example, let's add one more line of
115 code, where we print out the value of `x`:
116
117 ```{rust,ignore}
118 fn main() {
119     let x = Box::new(5);
120
121     add_one(x);
122
123     println!("{}", x);
124 }
125
126 fn add_one(mut num: Box<i32>) {
127     *num += 1;
128 }
129 ```
130
131 This does not compile, and gives us an error:
132
133 ```text
134 error: use of moved value: `x`
135    println!("{}", x);
136                   ^
137 ```
138
139 Remember, we need one deallocation for every allocation. When we try to pass
140 our box to `add_one`, we would have two handles to the memory: `x` in `main`,
141 and `num` in `add_one`. If we deallocated the memory when each handle went out
142 of scope, we would have two deallocations and one allocation, and that's wrong.
143 So when we call `add_one`, Rust defines `num` as the owner of the handle. And
144 so, now that we've given ownership to `num`, `x` is invalid. `x`'s value has
145 "moved" from `x` to `num`. Hence the error: use of moved value `x`.
146
147 To fix this, we can have `add_one` give ownership back when it's done with the
148 box:
149
150 ```rust
151 fn main() {
152     let x = Box::new(5);
153
154     let y = add_one(x);
155
156     println!("{}", y);
157 }
158
159 fn add_one(mut num: Box<i32>) -> Box<i32> {
160     *num += 1;
161
162     num
163 }
164 ```
165
166 This code will compile and run just fine. Now, we return a `box`, and so the
167 ownership is transferred back to `y` in `main`. We only have ownership for the
168 duration of our function before giving it back. This pattern is very common,
169 and so Rust introduces a concept to describe a handle which temporarily refers
170 to something another handle owns. It's called *borrowing*, and it's done with
171 *references*, designated by the `&` symbol.
172
173 # Borrowing
174
175 Here's the current state of our `add_one` function:
176
177 ```rust
178 fn add_one(mut num: Box<i32>) -> Box<i32> {
179     *num += 1;
180
181     num
182 }
183 ```
184
185 This function takes ownership, because it takes a `Box`, which owns its
186 contents. But then we give ownership right back.
187
188 In the physical world, you can give one of your possessions to someone for a
189 short period of time. You still own your possession, you're just letting someone
190 else use it for a while. We call that *lending* something to someone, and that
191 person is said to be *borrowing* that something from you.
192
193 Rust's ownership system also allows an owner to lend out a handle for a limited
194 period. This is also called *borrowing*. Here's a version of `add_one` which
195 borrows its argument rather than taking ownership:
196
197 ```rust
198 fn add_one(num: &mut i32) {
199     *num += 1;
200 }
201 ```
202
203 This function borrows an `i32` from its caller, and then increments it. When
204 the function is over, and `num` goes out of scope, the borrow is over.
205
206 We have to change our `main` a bit too:
207
208 ```rust
209 fn main() {
210     let mut x = 5;
211
212     add_one(&mut x);
213
214     println!("{}", x);
215 }
216
217 fn add_one(num: &mut i32) {
218     *num += 1;
219 }
220 ```
221
222 We don't need to assign the result of `add_one()` anymore, because it doesn't
223 return anything anymore. This is because we're not passing ownership back,
224 since we just borrow, not take ownership.
225
226 # Lifetimes
227
228 Lending out a reference to a resource that someone else owns can be
229 complicated, however. For example, imagine this set of operations:
230
231 1. I acquire a handle to some kind of resource.
232 2. I lend you a reference to the resource.
233 3. I decide I'm done with the resource, and deallocate it, while you still have
234    your reference.
235 4. You decide to use the resource.
236
237 Uh oh! Your reference is pointing to an invalid resource. This is called a
238 *dangling pointer* or "use after free," when the resource is memory.
239
240 To fix this, we have to make sure that step four never happens after step
241 three. The ownership system in Rust does this through a concept called
242 *lifetimes*, which describe the scope that a reference is valid for.
243
244 Remember the function that borrowed an `i32`? Let's look at it again.
245
246 ```rust
247 fn add_one(num: &i32) -> i32 {
248     *num + 1
249 }
250 ```
251
252 Rust has a feature called *lifetime elision*, which allows you to not write
253 lifetime annotations in certain circumstances. This is one of them. We will
254 cover the others later. Without eliding the lifetimes, `add_one` looks like
255 this:
256
257 ```rust
258 fn add_one<'a>(num: &'a i32) -> i32 {
259     *num + 1
260 }
261 ```
262
263 The `'a` is called a *lifetime*. Most lifetimes are used in places where
264 short names like `'a`, `'b` and `'c` are clearest, but it's often useful to
265 have more descriptive names. Let's dig into the syntax in a bit more detail:
266
267 ```{rust,ignore}
268 fn add_one<'a>(...)
269 ```
270
271 This part _declares_ our lifetimes. This says that `add_one` has one lifetime,
272 `'a`. If we had two, it would look like this:
273
274 ```{rust,ignore}
275 fn add_two<'a, 'b>(...)
276 ```
277
278 Then in our parameter list, we use the lifetimes we've named:
279
280 ```{rust,ignore}
281 ...(num: &'a i32) -> ...
282 ```
283
284 If you compare `&i32` to `&'a i32`, they're the same, it's just that the
285 lifetime `'a` has snuck in between the `&` and the `i32`. We read `&i32` as "a
286 reference to an i32" and `&'a i32` as "a reference to an i32 with the lifetime 'a.'"
287
288 Why do lifetimes matter? Well, for example, here's some code:
289
290 ```rust
291 struct Foo<'a> {
292     x: &'a i32,
293 }
294
295 fn main() {
296     let y = &5; // this is the same as `let _y = 5; let y = &_y;
297     let f = Foo { x: y };
298
299     println!("{}", f.x);
300 }
301 ```
302
303 As you can see, `struct`s can also have lifetimes. In a similar way to functions,
304
305 ```{rust}
306 struct Foo<'a> {
307 # x: &'a i32,
308 # }
309 ```
310
311 declares a lifetime, and
312
313 ```rust
314 # struct Foo<'a> {
315 x: &'a i32,
316 # }
317 ```
318
319 uses it. So why do we need a lifetime here? We need to ensure that any reference
320 to a `Foo` cannot outlive the reference to an `i32` it contains.
321
322 ## Thinking in scopes
323
324 A way to think about lifetimes is to visualize the scope that a reference is
325 valid for. For example:
326
327 ```rust
328 fn main() {
329     let y = &5;     // -+ y goes into scope
330                     //  |
331     // stuff        //  |
332                     //  |
333 }                   // -+ y goes out of scope
334 ```
335
336 Adding in our `Foo`:
337
338 ```rust
339 struct Foo<'a> {
340     x: &'a i32,
341 }
342
343 fn main() {
344     let y = &5;           // -+ y goes into scope
345     let f = Foo { x: y }; // -+ f goes into scope
346     // stuff              //  |
347                           //  |
348 }                         // -+ f and y go out of scope
349 ```
350
351 Our `f` lives within the scope of `y`, so everything works. What if it didn't?
352 This code won't work:
353
354 ```{rust,ignore}
355 struct Foo<'a> {
356     x: &'a i32,
357 }
358
359 fn main() {
360     let x;                    // -+ x goes into scope
361                               //  |
362     {                         //  |
363         let y = &5;           // ---+ y goes into scope
364         let f = Foo { x: y }; // ---+ f goes into scope
365         x = &f.x;             //  | | error here
366     }                         // ---+ f and y go out of scope
367                               //  |
368     println!("{}", x);        //  |
369 }                             // -+ x goes out of scope
370 ```
371
372 Whew! As you can see here, the scopes of `f` and `y` are smaller than the scope
373 of `x`. But when we do `x = &f.x`, we make `x` a reference to something that's
374 about to go out of scope.
375
376 Named lifetimes are a way of giving these scopes a name. Giving something a
377 name is the first step towards being able to talk about it.
378
379 ## 'static
380
381 The lifetime named *static* is a special lifetime. It signals that something
382 has the lifetime of the entire program. Most Rust programmers first come across
383 `'static` when dealing with strings:
384
385 ```rust
386 let x: &'static str = "Hello, world.";
387 ```
388
389 String literals have the type `&'static str` because the reference is always
390 alive: they are baked into the data segment of the final binary. Another
391 example are globals:
392
393 ```rust
394 static FOO: i32 = 5;
395 let x: &'static i32 = &FOO;
396 ```
397
398 This adds an `i32` to the data segment of the binary, and `FOO` is a reference
399 to it.
400
401 # Shared Ownership
402
403 In all the examples we've considered so far, we've assumed that each handle has
404 a singular owner. But sometimes, this doesn't work. Consider a car. Cars have
405 four wheels. We would want a wheel to know which car it was attached to. But
406 this won't work:
407
408 ```{rust,ignore}
409 struct Car {
410     name: String,
411 }
412
413 struct Wheel {
414     size: i32,
415     owner: Car,
416 }
417
418 fn main() {
419     let car = Car { name: "DeLorean".to_string() };
420
421     for _ in range(0u, 4) {
422         Wheel { size: 360, owner: car };
423     }
424 }
425 ```
426
427 We try to make four `Wheel`s, each with a `Car` that it's attached to. But the
428 compiler knows that on the second iteration of the loop, there's a problem:
429
430 ```text
431 error: use of moved value: `car`
432     Wheel { size: 360, owner: car };
433                               ^~~
434 note: `car` moved here because it has type `Car`, which is non-copyable
435     Wheel { size: 360, owner: car };
436                               ^~~
437 ```
438
439 We need our `Car` to be pointed to by multiple `Wheel`s. We can't do that with
440 `Box<T>`, because it has a single owner. We can do it with `Rc<T>` instead:
441
442 ```rust
443 use std::rc::Rc;
444
445 struct Car {
446     name: String,
447 }
448
449 struct Wheel {
450     size: i32,
451     owner: Rc<Car>,
452 }
453
454 fn main() {
455     let car = Car { name: "DeLorean".to_string() };
456
457     let car_owner = Rc::new(car);
458
459     for _ in range(0u, 4) {
460         Wheel { size: 360, owner: car_owner.clone() };
461     }
462 }
463 ```
464
465 We wrap our `Car` in an `Rc<T>`, getting an `Rc<Car>`, and then use the
466 `clone()` method to make new references. We've also changed our `Wheel` to have
467 an `Rc<Car>` rather than just a `Car`.
468
469 This is the simplest kind of multiple ownership possible. For example, there's
470 also `Arc<T>`, which uses more expensive atomic instructions to be the
471 thread-safe counterpart of `Rc<T>`.
472
473 ## Lifetime Elision
474
475 Earlier, we mentioned *lifetime elision*, a feature of Rust which allows you to
476 not write lifetime annotations in certain circumstances. All references have a
477 lifetime, and so if you elide a lifetime (like `&T` instead of `&'a T`), Rust
478 will do three things to determine what those lifetimes should be.
479
480 When talking about lifetime elision, we use the term *input lifetime* and
481 *output lifetime*. An *input lifetime* is a lifetime associated with a parameter
482 of a function, and an *output lifetime* is a lifetime associated with the return
483 value of a function. For example, this function has an input lifetime:
484
485 ```{rust,ignore}
486 fn foo<'a>(bar: &'a str)
487 ```
488
489 This one has an output lifetime:
490
491 ```{rust,ignore}
492 fn foo<'a>() -> &'a str
493 ```
494
495 This one has a lifetime in both positions:
496
497 ```{rust,ignore}
498 fn foo<'a>(bar: &'a str) -> &'a str
499 ```
500
501 Here are the three rules:
502
503 * Each elided lifetime in a function's arguments becomes a distinct lifetime
504   parameter.
505
506 * If there is exactly one input lifetime, elided or not, that lifetime is
507   assigned to all elided lifetimes in the return values of that function.
508
509 * If there are multiple input lifetimes, but one of them is `&self` or `&mut
510   self`, the lifetime of `self` is assigned to all elided output lifetimes.
511
512 Otherwise, it is an error to elide an output lifetime.
513
514 ### Examples
515
516 Here are some examples of functions with elided lifetimes, and the version of
517 what the elided lifetimes are expand to:
518
519 ```{rust,ignore}
520 fn print(s: &str);                                      // elided
521 fn print<'a>(s: &'a str);                               // expanded
522
523 fn debug(lvl: u32, s: &str);                           // elided
524 fn debug<'a>(lvl: u32, s: &'a str);                    // expanded
525
526 // In the preceeding example, `lvl` doesn't need a lifetime because it's not a
527 // reference (`&`). Only things relating to references (such as a `struct`
528 // which contains a reference) need lifetimes.
529
530 fn substr(s: &str, until: u32) -> &str;                // elided
531 fn substr<'a>(s: &'a str, until: u32) -> &'a str;      // expanded
532
533 fn get_str() -> &str;                                   // ILLEGAL, no inputs
534
535 fn frob(s: &str, t: &str) -> &str;                      // ILLEGAL, two inputs
536
537 fn get_mut(&mut self) -> &mut T;                        // elided
538 fn get_mut<'a>(&'a mut self) -> &'a mut T;              // expanded
539
540 fn args<T:ToCStr>(&mut self, args: &[T]) -> &mut Command                  // elided
541 fn args<'a, 'b, T:ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command // expanded
542
543 fn new(buf: &mut [u8]) -> BufWriter;                    // elided
544 fn new<'a>(buf: &'a mut [u8]) -> BufWriter<'a>          // expanded
545 ```
546
547 # Related Resources
548
549 Coming Soon.