Skip to content

Commit 60bd3fb

Browse files
store Person.age on the heap
I think that `ref` is not required in this example if Person.age is stored on the stack, as the definition of `age` copies the data instead of moving it. I have thus changed the code to store it on the heap, to illustrate the usefulness of `ref` in this context, and added a short explanation. An alternative possibility could be to use `name` instead of `age` for the illustration; not sure which is clearer. Please feel free to edit or request edits to this PR if you see a clearer way!
1 parent 1ca6a7b commit 60bd3fb

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

src/scope/move/partial_move.md

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -13,12 +13,12 @@ fn main() {
1313
#[derive(Debug)]
1414
struct Person {
1515
name: String,
16-
age: u8,
16+
age: Box<u8>,
1717
}
1818
1919
let person = Person {
2020
name: String::from("Alice"),
21-
age: 20,
21+
age: Box::new(20),
2222
};
2323
2424
// `name` is moved out of person, but `age` is referenced
@@ -35,6 +35,13 @@ fn main() {
3535
println!("The person's age from person struct is {}", person.age);
3636
}
3737
```
38+
(In this example, we store the `age` variable on the heap to
39+
illustrate the partial move: deleting `ref` in the above code would
40+
give an error as the ownership of `person.age` would be moved to the
41+
variable `age`. If `Person.age` were stored on the stack, `ref`would
42+
not be required as the definition of `age` would copy the data from
43+
`person.age` without moving it.)
44+
3845
### See also:
3946
[destructuring][destructuring]
4047

0 commit comments

Comments
 (0)