Skip to content

Commit b26c4b6

Browse files
petrochenkovsteveklabnik
authored andcommitted
Add a paragraph about slice patterns
1 parent 138abdd commit b26c4b6

File tree

1 file changed

+19
-0
lines changed

1 file changed

+19
-0
lines changed

src/expressions/match-expr.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,25 @@ backwards compatibility.
140140
Range patterns only work [`char`] and [numeric types]. A range pattern may not
141141
be a sub-range of another range pattern inside the same `match`.
142142

143+
Slice patterns can match both arrays of fixed size and slices of dynamic size.
144+
```rust
145+
// Fixed size
146+
let arr = [1, 2, 3];
147+
match arr {
148+
[1, _, _] => "starts with one",
149+
[a, b, c] => "starts with something else",
150+
}
151+
```
152+
```rust
153+
// Dynamic size
154+
let v = vec![1, 2, 3];
155+
match v[..] {
156+
[a, b] => { /* this arm will not apply because the length doesn't match */ }
157+
[a, b, c] => { /* this arm will apply */ }
158+
_ => { /* this wildcard is required, since we don't know length statically */ }
159+
}
160+
```
161+
143162
Finally, match patterns can accept *pattern guards* to further refine the
144163
criteria for matching a case. Pattern guards appear after the pattern and
145164
consist of a bool-typed expression following the `if` keyword. A pattern guard

0 commit comments

Comments
 (0)