Skip to content

Commit 6216f45

Browse files
committed
Add more details to patterns.
1 parent 61b7fa3 commit 6216f45

File tree

1 file changed

+34
-0
lines changed

1 file changed

+34
-0
lines changed

src/patterns.md

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -241,6 +241,37 @@ Thus, `ref` is not something that is being matched against. Its objective is
241241
exclusively to make the matched binding a reference, instead of potentially
242242
copying or moving what was matched.
243243

244+
[Path patterns](#path-patterns) take precedence over identifier patterns. It is an error
245+
if `ref` or `ref mut` is specified and the identifier shadows a constant.
246+
247+
### Binding modes
248+
249+
In order to service better ergonomics, patterns operate in different *binding modes* in
250+
order to make it easier to bind references to values. When a reference value is matched by
251+
a non-reference pattern, it will be automatically treated as a `ref` or `ref mut` binding.
252+
Example:
253+
254+
```rust
255+
let x: &Option<i32> = &Some(3);
256+
if let Some(y) = x {
257+
// y was converted to `ref y` and its type is &i32
258+
}
259+
```
260+
261+
*Non-reference patterns* include all patterns except bindings, [wildcard
262+
patterns](#wildcard-pattern) (`_`), [`const` patterns](#path-patterns) of reference types,
263+
and [reference patterns](#reference-patterns).
264+
265+
If a binding pattern does not explicitly have `ref`, `ref mut`, or `mut`, then it uses the
266+
*default binding mode* to determine how the variable should be bound. The default binding
267+
mode starts in "move" mode which uses move semantics. When matching a pattern, the
268+
compiler starts from the outside of the pattern and works inwards. Each time a reference
269+
is matched using a non-reference pattern, it will automatically dereference the value and
270+
update the default binding mode. References will set the default binding mode to `ref`.
271+
Mutable references will set the mode to `ref mut` unless the mode is already `ref` in
272+
which case it remains `ref`. If the automatically dereferenced value is still a reference,
273+
it is dereferenced and this process repeats.
274+
244275
## Wildcard pattern
245276

246277
> **<sup>Syntax</sup>**\
@@ -592,6 +623,9 @@ Unqualified path patterns can refer to:
592623

593624
Qualified path patterns can only refer to associated constants.
594625

626+
Constants cannot be a union type. Struct and enum constants must have
627+
`#[derive(PartialEq, Eq)]` (not merely implemented).
628+
595629
Path patterns are irrefutable when they refer to structs or an enum variant when the enum
596630
has only one variant or a constant whose type is irrefutable. They are refutable when they
597631
refer to refutable constants or enum variants for enums with multiple variants.

0 commit comments

Comments
 (0)