Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Document or-patterns #957
Document or-patterns #957
Changes from all commits
940de70
1be55f9
4c75c0b
245b833
f567a17
45753be
100fa06
4b574ca
629e7df
File filter
Filter by extension
Conversations
Jump to
There are no files selected for viewing
Patterns
Patterns are used to match values against structures and to, optionally, bind variables to values inside these structures. They are also used in variable declarations and parameters for functions and closures.
The pattern in the following example does four things:
person
has thecar
field filled with something.age
field is between 13 and 19, and binds its value to theperson_age
variable.name
field to the variableperson_name
.person
. The remaining fields can have any value and are not bound to any variables.Patterns are used in:
let
declarationsmatch
expressionsif let
expressionswhile let
expressionsfor
expressionsDestructuring
Patterns can be used to destructure structs, enums, and tuples. Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values. In a pattern whose scrutinee expression has a
struct
,enum
ortuple
type, a placeholder (_
) stands in for a single data field, whereas a wildcard..
stands in for all the remaining fields of a particular variant. When destructuring a data structure with named (but not numbered) fields, it is allowed to writefieldname
as a shorthand forfieldname: fieldname
.Refutability
A pattern is said to be refutable when it has the possibility of not being matched by the value it is being matched against. Irrefutable patterns, on the other hand, always match the value they are being matched against. Examples:
Literal patterns
Literal patterns match exactly the same value as what is created by the literal. Since negative numbers are not literals, literal patterns also accept an optional minus sign before the literal, which acts like the negation operator.
Floating-point literals are currently accepted, but due to the complexity of comparing them, they are going to be forbidden on literal patterns in a future version of Rust (see issue #41620).
Literal patterns are always refutable.
Examples:
Identifier patterns
Identifier patterns bind the value they match to a variable. The identifier must be unique within the pattern. The variable will shadow any variables of the same name in scope. The scope of the new binding depends on the context of where the pattern is used (such as a
let
binding or amatch
arm).Patterns that consist of only an identifier, possibly with a
mut
, match any value and bind it to that identifier. This is the most commonly used pattern in variable declarations and parameters for functions and closures.To bind the matched value of a pattern to a variable, use the syntax
variable @ subpattern
. For example, the following binds the value 2 toe
(not the entire range: the range here is a range subpattern).By default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements
Copy
. This can be changed to bind to a reference by using theref
keyword, or to a mutable reference usingref mut
. For example:In the first match expression, the value is copied (or moved). In the second match, a reference to the same memory location is bound to the variable value. This syntax is needed because in destructuring subpatterns the
&
operator can't be applied to the value's fields. For example, the following is not valid:To make it valid, write the following:
Thus,
ref
is not something that is being matched against. Its objective is exclusively to make the matched binding a reference, instead of potentially copying or moving what was matched.Path patterns take precedence over identifier patterns. It is an error if
ref
orref mut
is specified and the identifier shadows a constant.Identifier patterns are irrefutable if the
@
subpattern is irrefutable or the subpattern is not specified.Binding modes
To service better ergonomics, patterns operate in different binding modes in order to make it easier to bind references to values. When a reference value is matched by a non-reference pattern, it will be automatically treated as a
ref
orref mut
binding. Example:Non-reference patterns include all patterns except bindings, wildcard patterns (
_
),const
patterns of reference types, and reference patterns.If a binding pattern does not explicitly have
ref
,ref mut
, ormut
, then it uses the default binding mode to determine how the variable is bound. The default binding mode starts in "move" mode which uses move semantics. When matching a pattern, the compiler starts from the outside of the pattern and works inwards. Each time a reference is matched using a non-reference pattern, it will automatically dereference the value and update the default binding mode. References will set the default binding mode toref
. Mutable references will set the mode toref mut
unless the mode is alreadyref
in which case it remainsref
. If the automatically dereferenced value is still a reference, it is dereferenced and this process repeats.Move bindings and reference bindings can be mixed together in the same pattern, doing so will result in partial move of the object bound to and the object cannot be used afterwards. This applies only if the type cannot be copied.
In the example below,
name
is moved out ofperson
, trying to useperson
as a whole orperson.name
would result in an error because of partial move.Example:
Wildcard pattern
The wildcard pattern (an underscore symbol) matches any value. It is used to ignore values when they don't matter. Inside other patterns it matches a single data field (as opposed to the
..
which matches the remaining fields). Unlike identifier patterns, it does not copy, move or borrow the value it matches.Examples:
The wildcard pattern is always irrefutable.
Rest patterns
The rest pattern (the
..
token) acts as a variable-length pattern which matches zero or more elements that haven't been matched already before and after. It may only be used in tuple, tuple struct, and slice patterns, and may only appear once as one of the elements in those patterns. It is also allowed in an identifier pattern for slice patterns only.The rest pattern is always irrefutable.
Examples:
Range patterns
Range patterns match values that are within the closed range defined by its lower and upper bounds. For example, a pattern
'm'..='p'
will match only the values'm'
,'n'
,'o'
, and'p'
. The bounds can be literals or paths that point to constant values.A pattern a
..=
b must always have a ≤ b. It is an error to have a range pattern10..=0
, for example.The
...
syntax is kept for backwards compatibility.Range patterns only work on scalar types. The accepted types are:
Examples:
Range patterns for (non-
usize
and -isize
) integer andchar
types are irrefutable when they span the entire set of possible values of a type. For example,0u8..=255u8
is irrefutable. The range of values for an integer type is the closed range from its minimum to maximum value. The range of values for achar
type are precisely those ranges containing all Unicode Scalar Values:'\u{0000}'..='\u{D7FF}'
and'\u{E000}'..='\u{10FFFF}'
.Reference patterns
Reference patterns dereference the pointers that are being matched and, thus, borrow them.
For example, these two matches on
x: &i32
are equivalent:The grammar production for reference patterns has to match the token
&&
to match a reference to a reference because it is a token by itself, not two&
tokens.Adding the
mut
keyword dereferences a mutable reference. The mutability must match the mutability of the reference.Reference patterns are always irrefutable.
Struct patterns
Struct patterns match struct values that match all criteria defined by its subpatterns. They are also used to destructure a struct.
On a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of
..
:If
..
is not used, it is required to match all fields:The
ref
and/ormut
IDENTIFIER syntax matches any value and binds it to a variable with the same name as the given field.A struct pattern is refutable when one of its subpatterns is refutable.
Tuple struct patterns
Tuple struct patterns match tuple struct and enum values that match all criteria defined by its subpatterns. They are also used to destructure a tuple struct or enum value.
A tuple struct pattern is refutable when one of its subpatterns is refutable.
Tuple patterns
Tuple patterns match tuple values that match all criteria defined by its subpatterns. They are also used to destructure a tuple.
The form
(..)
with a single RestPattern is a special form that does not require a comma, and matches a tuple of any size.The tuple pattern is refutable when one of its subpatterns is refutable.
An example of using tuple patterns:
Grouped patterns
Enclosing a pattern in parentheses can be used to explicitly control the precedence of compound patterns. For example, a reference pattern next to a range pattern such as
&0..=5
is ambiguous and is not allowed, but can be expressed with parentheses.Slice patterns
Slice patterns can match both arrays of fixed size and slices of dynamic size.
Slice patterns are irrefutable when matching an array as long as each element is irrefutable. When matching a slice, it is irrefutable only in the form with a single
..
rest pattern or identifier pattern with the..
rest pattern as a subpattern.Path patterns
Path patterns are patterns that refer either to constant values or to structs or enum variants that have no fields.
Unqualified path patterns can refer to:
Qualified path patterns can only refer to associated constants.
Constants cannot be a union type. Struct and enum constants must have
#[derive(PartialEq, Eq)]
(not merely implemented).Path patterns are irrefutable when they refer to structs or an enum variant when the enum has only one variant or a constant whose type is irrefutable. They are refutable when they refer to refutable constants or enum variants for enums with multiple variants.
Or-patterns
Or-patterns are patterns that match on one of two or more sub-patterns (e.g.
A | B | C
). They can nest arbitrarily. Syntactically, or-patterns are allowed in any of the places where other patterns are allowed (represented by the Pattern production), with the exceptions oflet
-bindings and function and closure arguments (represented by the PatternNoTopAlt production).Static semantics
Given a pattern
p | q
at some depth for some arbitrary patternsp
andq
, the pattern is considered ill-formed if:p
does not unify with the type inferred forq
, orp
andq
, orp
andq
do not unify with respect to types or binding modes.Unification of types is in all instances aforementioned exact and implicit type coercions do not apply.
When type checking an expression
match e_s { a_1 => e_1, ... a_n => e_n }
, for each match arma_i
which contains a pattern of formp_i | q_i
, the patternp_i | q_i
is considered ill formed if, at the depthd
where it exists the fragment ofe_s
at depthd
, the type of the expression fragment does not unify withp_i | q_i
.With respect to exhaustiveness checking, a pattern
p | q
is considered to coverp
as well asq
. For some constructorc(x, ..)
the distributive law applies such thatc(p | q, ..rest)
covers the same set of value asc(p, ..rest) | c(q, ..rest)
does. This can be applied recursively until there are no more nested patterns of formp | q
other than those that exist at the top level.Note that by "constructor" we do not refer to tuple struct patterns, but rather we refer to a pattern for any product type. This includes enum variants, tuple structs, structs with named fields, arrays, tuples, and slices.
Dynamic semantics
e_s
against a patternc(p | q, ..rest)
at depthd
wherec
is some constructor,p
andq
are arbitrary patterns, andrest
is optionally any remaining potential factors inc
, is defined as being the same as that ofc(p, ..rest) | c(q, ..rest)
.Precedence with other undelimited patterns
As shown elsewhere in this chapter, there are several types of patterns that are syntactically undelimited, including identifier patterns, reference patterns, and or-patterns. Or-patterns always have the lowest-precedence. This allows us to reserve syntactic space for a possible future type ascription feature and also to reduce ambiguity. For example,
x @ A(..) | B(..)
will result in an error thatx
is not bound in all patterns,&A(x) | B(x)
will result in a type mismatch betweenx
in the different subpatterns.