Patterns - The Rust Reference
Keyboard shortcuts Press ← or → to navigate between chapters Press S or / to search in the book Press ? to show this help Press Esc to hide this help The Rust Reference [patterns] Patterns [patterns .syntax] Syntax Pattern → | ? PatternNoTopAlt ( | PatternNoTopAlt ) * PatternNoTopAlt → PatternWithoutModernRange | ModernRangePattern PatternWithoutModernRange → LiteralPattern | IdentifierPattern | WildcardPattern | RestPattern | ReferencePattern | StructPattern | TupleStructPattern | TuplePattern | GroupedPattern | SlicePattern | PathPattern | MacroInvocation | ObsoleteRangePattern 1 [patterns .intro] 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: Tests if person has the car field filled with something. Tests if the person’s age field is between 13 and 19, and binds its value to the person_age variable. Binds a reference to the name field to the variable person_name . Ignores the rest of the fields of person . The remaining fields can have any value and are not bound to any variables. #![allow(unused)] fn main() { struct Car; struct Computer; struct Person { name: String, car: Option<Car>, computer: Option<Computer>, age: u8, } let person = Person { name: String::from("John"), car: Some(Car), computer: None, age: 15, }; if let Person { car: Some(_), age: person_age @ 13..=19, name: ref person_name, .. } = person { println!("{} has a car and is {} years old.", person_name, person_age); } } [patterns .use] Patterns are used in: [patterns .let] let declarations [patterns .param] Function and closure parameters [patterns .match] match expressions [patterns .if-let] if let expressions [patterns .while-let] while let expressions [patterns .for] for expressions [patterns .destructure] Destructuring [patterns .destructure .intro] 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. [patterns .destructure .wildcard] In a pattern whose scrutinee expression has a struct , enum or tuple type, a wildcard pattern ( _ ) stands in for a single data field, whereas an et cetera or rest pattern ( .. ) stands in for all the remaining fields of a particular variant. [patterns .destructure .named-field-shorthand] When destructuring a data structure with named (but not numbered) fields, it is allowed to write fieldname as a shorthand for fieldname: fieldname . #![allow(unused)] fn main() { enum Message { Quit, WriteString(String), Move { x: i32, y: i32 }, ChangeColor(u8, u8, u8), } let message = Message::Quit; match message { Message::Quit => println!("Quit"), Message::WriteString(write) => println!("{}", &write), Message::Move{ x, y: 0 } => println!("move {} horizontally", x), Message::Move{ .. } => println!("other move"), Message::ChangeColor { 0: red, 1: green, 2: _ } => { println!("color change, red: {}, green: {}", red, green); } }; } [patterns .refutable] 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: #![allow(unused)] fn main() { let (x, y) = (1, 2); // "(x, y)" is an irrefutable pattern if let (a, 3) = (1, 2) { // "(a, 3)" is refutable, and will not match panic!("Shouldn't reach here"); } else if let (a, 4) = (3, 4) { // "(a, 4)" is refutable, and will match println!("Matched ({}, 4)", a); } } [patterns .literal] Literal patterns [patterns .literal .syntax] Tests Tests with this rule: tests/ui/binop/binary-minus-without-space.rs Syntax LiteralPattern → - ?
LiteralExpression [patterns .literal .intro] Tests Tests with this rule: tests/ui/binop/binary-minus-without-space.rs Literal patterns match exactly the same value as what is created by the literal. Since negative numbers are not literals , literals in patterns may be prefixed by an optional minus sign, which acts like the negation operator. Warning C string and raw C string literals are accepted in literal patterns, but &CStr doesn’t implement structural equality ( #[derive(Eq, PartialEq)] ) and therefore any such match on a &CStr will be rejected with a type error. [patterns .literal .refutable] Literal patterns are always refutable.
Examples: #![allow(unused)] fn main() { for i in -2..5 { match i { -1 => println!("It's minus one"), 1 => println!("It's a one"), 2|4 => println!("It's either a two or a four"), _ => println!("Matched none of the arms"), } } } [patterns .ident] Identifier patterns [patterns .ident .syntax] Syntax IdentifierPattern → ref ? mut ? IDENTIFIER ( @ PatternNoTopAlt ) ? [patterns .ident .intro] Identifier patterns bind the value they match to a variable in the value namespace . [patterns .ident .unique] The identifier must be unique within the pattern. [patterns .ident .scope] 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 a match arm). [patterns .ident .bare] 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. #![allow(unused)] fn main() { let mut variable = 10; fn sum(x: i32, y: i32) -> i32 { x + y } } [patterns .ident .scrutinized] To bind the matched value of a pattern to a variable, use the syntax variable @ subpattern .
For example, the following binds the value 2 to e (not the entire range: the range here is a range subpattern). #![allow(unused)] fn main() { let x = 2; match x { e @ 1 ..= 5 => println!("got a range element {}", e), _ => println!("anything"), } } [patterns .ident .move] 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 . [patterns .ident .ref] This can be changed to bind to a reference by using the ref keyword, or to a mutable reference using ref mut .
For example: #![allow(unused)] fn main() { let a = Some(10); match a { None => (), Some(value) => (), } match a { None => (), Some(ref value) => (), } } 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: #![allow(unused)] fn main() { struct Person { name: String, age: u8, } let value = Person { name: String::from("John"), age: 23 }; if let Person { name: &person_name, age: 18..=150 } = value { } } To make it valid, write the following: #![allow(unused)] fn main() { struct Person { name: String, age: u8, } let value = Person { name: String::from("John"), age: 23 }; if let Person { name: ref person_name, age: 18..=150 } = value { } } [patterns .ident .ref-ignored] 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. [patterns .ident .precedent] Path patterns take precedence over identifier patterns. Note When a pattern is a single-segment identifier, the grammar is ambiguous whether it means an IdentifierPattern or a PathPattern . This ambiguity can only be resolved after name resolution . #![allow(unused)] fn main() { const EXPECTED_VALUE: u8 = 42; // ^^^^^^^^^^^^^^ That this constant is in scope affects how the // patterns below are treated. fn check_value(x: u8) -> Result<u8, u8> { match x { EXPECTED_VALUE => Ok(x), // ^^^^^^^^^^^^^^ Parsed as a `PathPattern` that resolves to //
The rest of this page is on the live site.