@@ -6,21 +6,31 @@ 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
+ 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).
11
12
12
13
``` rust
13
14
#![feature(deref_patterns)]
14
15
#![allow(incomplete_features)]
15
16
16
17
pub fn main () {
17
18
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 {
19
24
* x += 1 ;
20
25
}
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 );
23
32
}
33
+
24
34
assert_eq! (v , [Box :: new (Some (2 ))]);
25
35
}
26
36
```
@@ -31,18 +41,22 @@ when matching on nested structures:
31
41
``` rust
32
42
pub fn main () {
33
43
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 {
36
46
* x += 1 ;
37
47
}
38
48
}
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 ) ;
42
52
}
43
53
}
44
54
assert_eq! (v , [Box :: new (Some (2 ))]);
45
55
}
46
56
```
47
57
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