From dc3a39d807512c626495c16680df2fffc16e8722 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Mon, 1 Feb 2016 18:49:47 -0500 Subject: [PATCH 1/2] Explain behavior of _ Fixes #31154 --- src/doc/book/patterns.md | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/src/doc/book/patterns.md b/src/doc/book/patterns.md index 8e9e7246e56f0..39a9cb1885e84 100644 --- a/src/doc/book/patterns.md +++ b/src/doc/book/patterns.md @@ -173,7 +173,31 @@ let (x, _, z) = coordinate(); Here, we bind the first and last element of the tuple to `x` and `z`, but ignore the middle element. -Similarly, you can use `..` in a pattern to disregard multiple values. +It’s worth noting that using `_` never binds the value in the first place, +which means a value may not move: + +```rust +let tuple: (u32, String) = (5, String::from("five")); + +// Here, tuple is moved, because the String moved: +let (x, _s) = tuple; + +// The next line would give "error: use of partially moved value: `tuple`" +// println!("Tuple is: {:?}", tuple); + +// However, + +let tuple = (5, String::from("five")); + +// Here, tuple is _not_ moved, as the String was never moved, and u32 is Copy: +let (x, _) = tuple; + +// That means this works: +println!("Tuple is: {:?}", tuple); +``` + +In a similar fashion to `_`, you can use `..` in a pattern to disregard +multiple values: ```rust enum OptionalTuple { From 6c907212b446e1c39ddb6db621bb72c6d07255f6 Mon Sep 17 00:00:00 2001 From: Steve Klabnik Date: Tue, 2 Feb 2016 11:15:45 -0500 Subject: [PATCH 2/2] Add note about temporaries --- src/doc/book/patterns.md | 12 ++++++++++-- 1 file changed, 10 insertions(+), 2 deletions(-) diff --git a/src/doc/book/patterns.md b/src/doc/book/patterns.md index 39a9cb1885e84..6fd7f4cd4755a 100644 --- a/src/doc/book/patterns.md +++ b/src/doc/book/patterns.md @@ -196,8 +196,16 @@ let (x, _) = tuple; println!("Tuple is: {:?}", tuple); ``` -In a similar fashion to `_`, you can use `..` in a pattern to disregard -multiple values: +This also means that any temporary variables will be dropped at the end of the +statement: + +```rust +// Here, the String created will be dropped immediately, as it’s not bound: + +let _ = String::from(" hello ").trim(); +``` + +You can also use `..` in a pattern to disregard multiple values: ```rust enum OptionalTuple {