@@ -6,21 +6,31 @@ 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+ This feature permits pattern matching on [ smart pointers in the standard library] through their
10+ ` Deref ` target types, either implicitly or with explicit ` deref!(_) ` patterns (the syntax of which
11+ is currently a placeholder).
1112
1213``` rust
1314#![feature(deref_patterns)]
1415#![allow(incomplete_features)]
1516
1617pub fn main () {
1718 let mut v = vec! [Box :: new (Some (0 ))];
18- if let [Some (ref mut x )] = v {
19+
20+ // Implicit dereferences are inserted when a pattern can match against the
21+ // result of repeatedly dereferencing but can't match against a smart
22+ // pointer itself. This works alongside match ergonomics for references.
23+ if let [Some (x )] = & mut v {
1924 * x += 1 ;
2025 }
21- if let deref! ([deref! (Some (ref mut x ))]) = v {
22- * x += 1 ;
26+
27+ // Explicit `deref!(_)` patterns may instead be used when finer control is
28+ // needed, e.g. to dereference only a single smart pointer, or to bind the
29+ // the result of dereferencing to a variable.
30+ if let deref! ([deref! (opt_x @ Some (1 ))]) = & mut v {
31+ opt_x . as_mut (). map (| x | * x += 1 );
2332 }
33+
2434 assert_eq! (v , [Box :: new (Some (2 ))]);
2535}
2636```
@@ -31,18 +41,22 @@ when matching on nested structures:
3141``` rust
3242pub fn main () {
3343 let mut v = vec! [Box :: new (Some (0 ))];
34- if let [ref mut b ] = * v {
35- if let Some (ref mut x ) = * * b {
44+ if let [b ] = & mut * v {
45+ if let Some (x ) = & mut * * b {
3646 * x += 1 ;
3747 }
3848 }
39- if let [ref mut b ] = * v {
40- if let Some ( ref mut x ) = * * b {
41- * x += 1 ;
49+ if let [b ] = & mut * v {
50+ if let opt_x @ Some ( 1 ) = & mut * * b {
51+ opt_x . as_mut () . map ( | x | * x += 1 ) ;
4252 }
4353 }
4454 assert_eq! (v , [Box :: new (Some (2 ))]);
4555}
4656```
4757
48- [ library-defined smart pointers ] : https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors
58+ This does not yet implement the functionality of [ ` string_deref_patterns ` ] , but it is intended to
59+ supersede that feature once it supports matching with string literals.
60+
61+ [ smart pointers in the standard library ] : https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors
62+ [ `string_deref_patterns` ] : ./string-deref-patterns.md
0 commit comments