Skip to content

Commit fb1f8dd

Browse files
authored
Rollup merge of #116741 - mejrs:string_pat, r=fee1-dead
Document `string_deref_patterns` feature Rendered: ![image](https://github.com/rust-lang/rust/assets/59372212/aa3ef9e7-080d-4979-a363-3c24fe299c00)
2 parents e86e6b4 + 318813d commit fb1f8dd

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# `string_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 `String` to `&str` through [its `Deref` implementation].
10+
11+
```rust
12+
#![feature(string_deref_patterns)]
13+
14+
pub enum Value {
15+
String(String),
16+
Number(u32),
17+
}
18+
19+
pub fn is_it_the_answer(value: Value) -> bool {
20+
match value {
21+
Value::String("42") => true,
22+
Value::Number(42) => true,
23+
_ => false,
24+
}
25+
}
26+
```
27+
28+
Without this feature other constructs such as match guards have to be used.
29+
30+
```rust
31+
# pub enum Value {
32+
# String(String),
33+
# Number(u32),
34+
# }
35+
#
36+
pub fn is_it_the_answer(value: Value) -> bool {
37+
match value {
38+
Value::String(s) if s == "42" => true,
39+
Value::Number(42) => true,
40+
_ => false,
41+
}
42+
}
43+
```
44+
45+
[its `Deref` implementation]: https://doc.rust-lang.org/std/string/struct.String.html#impl-Deref-for-String

0 commit comments

Comments
 (0)