Skip to content

Commit

Permalink
Merge pull request #1377 from Amjad50/move_ref_pattern
Browse files Browse the repository at this point in the history
Add partial moves example for `move_ref_pattern` stabilization
  • Loading branch information
marioidival authored Oct 19, 2020
2 parents 1524759 + a422727 commit 16746d0
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/SUMMARY.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,7 @@
- [RAII](scope/raii.md)
- [Ownership and moves](scope/move.md)
- [Mutability](scope/move/mut.md)
- [Partial moves](scope/move/partial_move.md)
- [Borrowing](scope/borrow.md)
- [Mutability](scope/borrow/mut.md)
- [Aliasing](scope/borrow/alias.md)
Expand Down
40 changes: 40 additions & 0 deletions src/scope/move/partial_move.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
# Partial moves

Pattern bindings can have `by-move` and `by-reference` bindings at
the same time which is used in [destructuring]. Using these pattern
will result in partial move for the variable, which means that part
of the variable is moved while other parts stayed. In this case, the
parent variable cannot be used afterwards as a whole. However, parts
of it that are referenced and not moved can be used.

```rust,editable
fn main() {
#[derive(Debug)]
struct Person {
name: String,
age: u8,
}
let person = Person {
name: String::from("Alice"),
age: 20,
};
// `name` is moved out of person, but `age` is referenced
let Person { name, ref age } = person;
println!("The person's age is {}", age);
println!("The person's name is {}", name);
// Error! borrow of partially moved value: `person` partial move occurs
//println!("The person struct is {:?}", person);
// `person` cannot be used but `person.age` can be used as it is not moved
println!("The person's age from person struct is {}", person.age);
}
```
### See also:
[destructuring][destructuring]

[destructuring]: ../../flow_control/match/destructuring.md

0 comments on commit 16746d0

Please sign in to comment.