From 2da4327581886f2acd32b9c2030de922582c9e39 Mon Sep 17 00:00:00 2001 From: Amjad Alsharafi Date: Sat, 29 Aug 2020 17:50:22 +0800 Subject: [PATCH] Add partial moves example --- src/SUMMARY.md | 1 + src/scope/move/partial_move.md | 40 ++++++++++++++++++++++++++++++++++ 2 files changed, 41 insertions(+) create mode 100644 src/scope/move/partial_move.md diff --git a/src/SUMMARY.md b/src/SUMMARY.md index dfefcd5b90..216bceadfe 100644 --- a/src/SUMMARY.md +++ b/src/SUMMARY.md @@ -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) diff --git a/src/scope/move/partial_move.md b/src/scope/move/partial_move.md new file mode 100644 index 0000000000..7afa7e5419 --- /dev/null +++ b/src/scope/move/partial_move.md @@ -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 \ No newline at end of file