Skip to content

Commit b704983

Browse files
committed
Improve the ownership guide a tad
Fixes #19924
1 parent b21a6da commit b704983

File tree

1 file changed

+20
-4
lines changed

1 file changed

+20
-4
lines changed

src/doc/trpl/ownership.md

+20-4
Original file line numberDiff line numberDiff line change
@@ -81,7 +81,6 @@ therefore deallocates the memory for you. Here's the equivalent example in
8181
Rust:
8282

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

103102
```rust
104-
# use std::boxed::Box;
105103
fn main() {
106104
let x = Box::new(5);
107105

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

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

153150
```rust
154-
# use std::boxed::Box;
155151
fn main() {
156152
let x = Box::new(5);
157153

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

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+
210226
# Lifetimes
211227

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

0 commit comments

Comments
 (0)