Skip to content

Commit

Permalink
Improve the ownership guide a tad
Browse files Browse the repository at this point in the history
Fixes #19924
  • Loading branch information
steveklabnik committed Jan 12, 2015
1 parent b21a6da commit b704983
Showing 1 changed file with 20 additions and 4 deletions.
24 changes: 20 additions & 4 deletions src/doc/trpl/ownership.md
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,6 @@ therefore deallocates the memory for you. Here's the equivalent example in
Rust:

```rust
# use std::boxed::Box;
{
let x = Box::new(5);
}
Expand All @@ -101,7 +100,6 @@ This is pretty straightforward, but what happens when we want to pass our box
to a function? Let's look at some code:

```rust
# use std::boxed::Box;
fn main() {
let x = Box::new(5);

Expand All @@ -117,7 +115,6 @@ This code works, but it's not ideal. For example, let's add one more line of
code, where we print out the value of `x`:

```{rust,ignore}
# use std::boxed::Box;
fn main() {
let x = Box::new(5);
Expand Down Expand Up @@ -151,7 +148,6 @@ To fix this, we can have `add_one` give ownership back when it's done with the
box:

```rust
# use std::boxed::Box;
fn main() {
let x = Box::new(5);

Expand Down Expand Up @@ -207,6 +203,26 @@ fn add_one(num: &mut i32) {
This function borrows an `i32` from its caller, and then increments it. When
the function is over, and `num` goes out of scope, the borrow is over.

We have to change our `main` a bit too:

```rust
fn main() {
let mut x = 5;

add_one(&mut x);

println!("{}", x);
}

fn add_one(num: &mut i32) {
*num += 1;
}
```

We don't need to assign the result of `add_one()` anymore, because it doesn't
return anything anymore. This is because we're not passing ownership back,
since we just borrow, not take ownership.

# Lifetimes

Lending out a reference to a resource that someone else owns can be
Expand Down

0 comments on commit b704983

Please sign in to comment.