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