Skip to content

Commit 4bae102

Browse files
committed
add an unstable book chapter
1 parent dbfb59d commit 4bae102

File tree

1 file changed

+48
-0
lines changed

1 file changed

+48
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,48 @@
1+
# `deref_patterns`
2+
3+
The tracking issue for this feature is: [#87121]
4+
5+
[#87121]: https://github.com/rust-lang/rust/issues/87121
6+
7+
------------------------
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.
11+
12+
```rust
13+
#![feature(deref_patterns)]
14+
#![allow(incomplete_features)]
15+
16+
pub fn main() {
17+
let mut v = vec![Box::new(Some(0))];
18+
if let [Some(ref mut x)] = v {
19+
*x += 1;
20+
}
21+
if let deref!([deref!(Some(ref mut x))]) = v {
22+
*x += 1;
23+
}
24+
assert_eq!(v, [Box::new(Some(2))]);
25+
}
26+
```
27+
28+
Without this feature, it may be necessary to introduce temporaries to represent dereferenced places
29+
when matching on nested structures:
30+
31+
```rust
32+
pub fn main() {
33+
let mut v = vec![Box::new(Some(0))];
34+
if let [ref mut b] = *v {
35+
if let Some(ref mut x) = **b {
36+
*x += 1;
37+
}
38+
}
39+
if let [ref mut b] = *v {
40+
if let Some(ref mut x) = **b {
41+
*x += 1;
42+
}
43+
}
44+
assert_eq!(v, [Box::new(Some(2))]);
45+
}
46+
```
47+
48+
[library-defined smart pointers]: https://doc.rust-lang.org/std/ops/trait.DerefPure.html#implementors

0 commit comments

Comments
 (0)