Skip to content

[r+] Improve the ownership guide a tad #21029

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Jan 16, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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