Skip to content

Commit 16746d0

Browse files
authored
Merge pull request #1377 from Amjad50/move_ref_pattern
Add partial moves example for `move_ref_pattern` stabilization
2 parents 1524759 + a422727 commit 16746d0

File tree

2 files changed

+41
-0
lines changed

2 files changed

+41
-0
lines changed

src/SUMMARY.md

+1
Original file line numberDiff line numberDiff line change
@@ -116,6 +116,7 @@
116116
- [RAII](scope/raii.md)
117117
- [Ownership and moves](scope/move.md)
118118
- [Mutability](scope/move/mut.md)
119+
- [Partial moves](scope/move/partial_move.md)
119120
- [Borrowing](scope/borrow.md)
120121
- [Mutability](scope/borrow/mut.md)
121122
- [Aliasing](scope/borrow/alias.md)

src/scope/move/partial_move.md

+40
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,40 @@
1+
# Partial moves
2+
3+
Pattern bindings can have `by-move` and `by-reference` bindings at
4+
the same time which is used in [destructuring]. Using these pattern
5+
will result in partial move for the variable, which means that part
6+
of the variable is moved while other parts stayed. In this case, the
7+
parent variable cannot be used afterwards as a whole. However, parts
8+
of it that are referenced and not moved can be used.
9+
10+
```rust,editable
11+
fn main() {
12+
#[derive(Debug)]
13+
struct Person {
14+
name: String,
15+
age: u8,
16+
}
17+
18+
let person = Person {
19+
name: String::from("Alice"),
20+
age: 20,
21+
};
22+
23+
// `name` is moved out of person, but `age` is referenced
24+
let Person { name, ref age } = person;
25+
26+
println!("The person's age is {}", age);
27+
28+
println!("The person's name is {}", name);
29+
30+
// Error! borrow of partially moved value: `person` partial move occurs
31+
//println!("The person struct is {:?}", person);
32+
33+
// `person` cannot be used but `person.age` can be used as it is not moved
34+
println!("The person's age from person struct is {}", person.age);
35+
}
36+
```
37+
### See also:
38+
[destructuring][destructuring]
39+
40+
[destructuring]: ../../flow_control/match/destructuring.md

0 commit comments

Comments
 (0)