Skip to content

Commit 6de570f

Browse files
committed
auto merge of #16487 : steveklabnik/rust/guide_ownership, r=brson
Whew. This section was so important, I saved it for last. /cc @wycats, @nikomatsakis
2 parents 5305f9b + c47dfbb commit 6de570f

File tree

1 file changed

+167
-0
lines changed

1 file changed

+167
-0
lines changed

src/doc/guide.md

Lines changed: 167 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3668,6 +3668,173 @@ In order to truly understand this error, we have to learn a few new concepts:
36683668

36693669
## Ownership, borrowing, and lifetimes
36703670

3671+
Whenever a resource of some kind is created, something must be responsible
3672+
for destroying that resource as well. Given that we're discussing pointers
3673+
right now, let's discuss this in the context of memory allocation, though
3674+
it applies to other resources as well.
3675+
3676+
When you allocate heap memory, you need a mechanism to free that memory. Many
3677+
languages let the programmer control the allocation, and then use a garbage
3678+
collector to handle the deallocation. This is a valid, time-tested strategy,
3679+
but it's not without its drawbacks. Because the programmer does not have to
3680+
think as much about deallocation, allocation becomes something commonplace,
3681+
because it's easy. And if you need precise control over when something is
3682+
deallocated, leaving it up to your runtime can make this difficult.
3683+
3684+
Rust chooses a different path, and that path is called **ownership**. Any
3685+
binding that creates a resource is the **owner** of that resource. Being an
3686+
owner gives you three privileges, with two restrictions:
3687+
3688+
1. You control when that resource is deallocated.
3689+
2. You may lend that resource, immutably, to as many borrowers as you'd like.
3690+
3. You may lend that resource, mutably, to a single borrower. **BUT**
3691+
4. Once you've done so, you may not also lend it out otherwise, mutably or
3692+
immutably.
3693+
5. You may not lend it out mutably if you're currently lending it to someone.
3694+
3695+
What's up with all this 'lending' and 'borrowing'? When you allocate memory,
3696+
you get a pointer to that memory. This pointer allows you to manipulate said
3697+
memory. If you are the owner of a pointer, then you may allow another
3698+
binding to temporarily borrow that pointer, and then they can manipulate the
3699+
memory. The length of time that the borrower is borrowing the pointer
3700+
from you is called a **lifetime**.
3701+
3702+
If two distinct bindings share a pointer, and the memory that pointer points to
3703+
is immutable, then there are no problems. But if it's mutable, both pointers
3704+
can attempt to write to the memory at the same time, causing a **race
3705+
condition**. Therefore, if someone wants to mutate something that they've
3706+
borrowed from you, you must not have lent out that pointer to anyone else.
3707+
3708+
Rust has a sophisticated system called the **borrow checker** to make sure that
3709+
everyone plays by these rules. At compile time, it verifies that none of these
3710+
rules are broken. If there's no problem, our program compiles successfully, and
3711+
there is no runtime overhead for any of this. The borrow checker works only at
3712+
compile time. If the borrow checker did find a problem, it will report a
3713+
**lifetime error**, and your program will refuse to compile.
3714+
3715+
That's a lot to take in. It's also one of the _most_ important concepts in
3716+
all of Rust. Let's see this syntax in action:
3717+
3718+
```{rust}
3719+
{
3720+
let x = 5i; // x is the owner of this integer, which is memory on the stack.
3721+
3722+
// other code here...
3723+
3724+
} // privilege 1: when x goes out of scope, this memory is deallocated
3725+
3726+
/// this function borrows an integer. It's given back automatically when the
3727+
/// function returns.
3728+
fn foo(x: &int) -> &int { x }
3729+
3730+
{
3731+
let x = 5i; // x is the owner of this integer, which is memory on the stack.
3732+
3733+
// privilege 2: you may lend that resource, to as many borrowers as you'd like
3734+
let y = &x;
3735+
let z = &x;
3736+
3737+
foo(&x); // functions can borrow too!
3738+
3739+
let a = &x; // we can do this alllllll day!
3740+
}
3741+
3742+
{
3743+
let mut x = 5i; // x is the owner of this integer, which is memory on the stack.
3744+
3745+
let y = &mut x; // privilege 3: you may lend that resource to a single borrower,
3746+
// mutably
3747+
}
3748+
```
3749+
3750+
If you are a borrower, you get a few privileges as well, but must also obey a
3751+
restriction:
3752+
3753+
1. If the borrow is immutable, you may read the data the pointer points to.
3754+
2. If the borrow is mutable, you may read and write the data the pointer points to.
3755+
3. You may lend the pointer to someone else in an immutable fashion, **BUT**
3756+
4. When you do so, they must return it to you before you must give your own
3757+
borrow back.
3758+
3759+
This last requirement can seem odd, but it also makes sense. If you have to
3760+
return something, and you've lent it to someone, they need to give it back to
3761+
you for you to give it back! If we didn't, then the owner could deallocate
3762+
the memory, and the person we've loaned it out to would have a pointer to
3763+
invalid memory. This is called a 'dangling pointer.'
3764+
3765+
Let's re-examine the error that led us to talk about all of this, which was a
3766+
violation of the restrictions placed on owners who lend something out mutably.
3767+
The code:
3768+
3769+
```{rust,ignore}
3770+
let mut x = 5i;
3771+
let y = &mut x;
3772+
let z = &mut x;
3773+
```
3774+
3775+
The error:
3776+
3777+
```{notrust,ignore}
3778+
error: cannot borrow `x` as mutable more than once at a time
3779+
let z = &mut x;
3780+
^
3781+
note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3782+
let y = &mut x;
3783+
^
3784+
note: previous borrow ends here
3785+
fn main() {
3786+
let mut x = 5i;
3787+
let y = &mut x;
3788+
let z = &mut x;
3789+
}
3790+
^
3791+
```
3792+
3793+
This error comes in three parts. Let's go over each in turn.
3794+
3795+
```{notrust,ignore}
3796+
error: cannot borrow `x` as mutable more than once at a time
3797+
let z = &mut x;
3798+
^
3799+
```
3800+
3801+
This error states the restriction: you cannot lend out something mutable more
3802+
than once at the same time. The borrow checker knows the rules!
3803+
3804+
```{notrust,ignore}
3805+
note: previous borrow of `x` occurs here; the mutable borrow prevents subsequent moves, borrows, or modification of `x` until the borrow ends
3806+
let y = &mut x;
3807+
^
3808+
```
3809+
3810+
Some compiler errors come with notes to help you fix the error. This error comes
3811+
with two notes, and this is the first. This note informs us of exactly where
3812+
the first mutable borrow occurred. The error showed us the second. So now we
3813+
see both parts of the problem. It also alludes to rule #3, by reminding us that
3814+
we can't change `x` until the borrow is over.
3815+
3816+
```{notrust,ignore}
3817+
note: previous borrow ends here
3818+
fn main() {
3819+
let mut x = 5i;
3820+
let y = &mut x;
3821+
let z = &mut x;
3822+
}
3823+
^
3824+
```
3825+
3826+
Here's the second note, which lets us know where the first borrow would be over.
3827+
This is useful, because if we wait to try to borrow `x` after this borrow is
3828+
over, then everything will work.
3829+
3830+
These rules are very simple, but that doesn't mean that they're easy. For more
3831+
advanced patterns, please consult the [Lifetime Guide](guide-lifetimes.html).
3832+
You'll also learn what this type signature with the `'a` syntax is:
3833+
3834+
```{rust,ignore}
3835+
pub fn as_maybe_owned(&self) -> MaybeOwned<'a> { ... }
3836+
```
3837+
36713838
## Boxes
36723839

36733840
All of our references so far have been to variables we've created on the stack.

0 commit comments

Comments
 (0)