@@ -6,21 +6,34 @@ The tracking issue for this feature is: [#87121]
66
77------------------------
88
9- This feature permits pattern matching on [ library-defined smart pointers] through their ` Deref `
10- target types, either implicitly or with the placeholder ` deref!(_) ` syntax.
9+ > ** Note** : This feature is incomplete. In the future, it is meant to supersede
10+ > [ ` box_patterns ` ] ( ./box-patterns.md ) and [ ` string_deref_patterns ` ] ( ./string-deref-patterns.md ) .
11+
12+ This feature permits pattern matching on [ smart pointers in the standard library] through their
13+ ` Deref ` target types, either implicitly or with explicit ` deref!(_) ` patterns (the syntax of which
14+ is currently a placeholder).
1115
1216``` rust
1317#![feature(deref_patterns)]
1418#![allow(incomplete_features)]
1519
1620pub fn main () {
1721 let mut v = vec! [Box :: new (Some (0 ))];
18- if let [Some (ref mut x )] = v {
22+
23+ // Implicit dereferences are inserted when a pattern can match against the
24+ // result of repeatedly dereferencing but can't match against a smart
25+ // pointer itself. This works alongside match ergonomics for references.
26+ if let [Some (x )] = & mut v {
1927 * x += 1 ;
2028 }
21- if let deref! ([deref! (Some (ref mut x ))]) = v {
22- * x += 1 ;
29+
30+ // Explicit `deref!(_)` patterns may instead be used when finer control is
31+ // needed, e.g. to dereference only a single smart pointer, or to bind the
32+ // the result of dereferencing to a variable.
33+ if let deref! ([deref! (opt_x @ Some (1 ))]) = & mut v {
34+ opt_x . as_mut (). map (| x | * x += 1 );
2335 }
36+
2437 assert_eq! (v , [Box :: new (Some (2 ))]);
2538}
2639```
@@ -31,18 +44,18 @@ when matching on nested structures:
3144``` rust
3245pub fn main () {
3346 let mut v = vec! [Box :: new (Some (0 ))];
34- if let [ref mut b ] = * v {
35- if let Some (ref mut x ) = * * b {
47+ if let [b ] = & mut * v {
48+ if let Some (x ) = & mut * * b {
3649 * x += 1 ;
3750 }
3851 }
39- if let [ref mut b ] = * v {
40- if let Some ( ref mut x ) = * * b {
41- * x += 1 ;
52+ if let [b ] = & mut * v {
53+ if let opt_x @ Some ( 1 ) = & mut * * b {
54+ opt_x . as_mut () . map ( | x | * x += 1 ) ;
4255 }
4356 }
4457 assert_eq! (v , [Box :: new (Some (2 ))]);
4558}
4659```
4760
48- [ library-defined smart pointers] : https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors
61+ [ smart pointers in the standard library ] : https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors
0 commit comments