@@ -6,21 +6,34 @@ The tracking issue for this feature is: [#87121]
6
6
7
7
------------------------
8
8
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).
11
15
12
16
``` rust
13
17
#![feature(deref_patterns)]
14
18
#![allow(incomplete_features)]
15
19
16
20
pub fn main () {
17
21
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 {
19
27
* x += 1 ;
20
28
}
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 );
23
35
}
36
+
24
37
assert_eq! (v , [Box :: new (Some (2 ))]);
25
38
}
26
39
```
@@ -31,18 +44,18 @@ when matching on nested structures:
31
44
``` rust
32
45
pub fn main () {
33
46
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 {
36
49
* x += 1 ;
37
50
}
38
51
}
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 ) ;
42
55
}
43
56
}
44
57
assert_eq! (v , [Box :: new (Some (2 ))]);
45
58
}
46
59
```
47
60
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