The Rust Reference › Array and array index expressions › Array and slice indexing expressions

```grammar,expressions
IndexExpression -> Expression `[` Expression `]`
```
[Array] and [slice]-typed values can be indexed by writing a square-bracket-enclosed expression of type `usize` (the index) after them. When the array is mutable, the resulting [memory location] can be assigned to.
For other types an index expression `a[b]` is equivalent to `*std::ops::Index::index(&a, b)`, or `*std::ops::IndexMut::index_mut(&mut a, b)` in a mutable place expression context, except that when the index expression undergoes [temporary lifetime extension], the indexed expression `a` also has its [temporary scope] extended. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.
```rust
// The temporary holding the result of `vec![()]` is extended to
// live to the end of the block, so `x` may be used in subsequent
// statements.
let x = &vec();
```
```rust,compile_fail,E0716
// The temporary holding the result of `vec![()]` is dropped at the
// end of the statement, so it's an error to use `y` after.
let y = &*std::ops::Index::index(&vec![()], 0); // ERROR
```
Indices are zero-based for arrays and slices.
Array access is a [constant expression], so bounds can be checked at compile-time with a constant index value. Otherwise a check will be performed at run-time that will put the thread in a _panicked state_ if it fails.

Array and array index expressions
Array and slice indexing expressions


The Rust Reference › Array and array index expressions › Array and slice indexing expressions

```rust,should_panic
// lint is deny by default.
#![warn(unconditional_panic)]

([1, 2, 3, 4])[2];        // Evaluates to 3

let b = [[1, 0, 0], [0, 1, 0], [0, 0, 1]];
b1;                  // multidimensional array indexing

let x = (["a", "b"])[10]; // warning: index out of bounds

let n = 10;
let y = (["a", "b"])[n];  // panics

let arr = ["a", "b"];
arr[10];                  // warning: index out of bounds
```
The array index expression can be implemented for types other than arrays and slices by implementing the [Index] and [IndexMut] traits.


The Rust Reference › Tuple and tuple indexing expressions › Tuple expressions

```grammar,expressions
TupleExpression -> `(` TupleElements? `)`

TupleElements -> ( Expression `,` )+ Expression?
```
A *tuple expression* constructs tuple values.
The syntax for tuple expressions is a parenthesized, comma separated list of expressions, called the *tuple initializer operands*.
1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with a [parenthetical expression].
Tuple expressions are a [value expression] that evaluate into a newly constructed value of a tuple type.
The number of tuple initializer operands is the arity of the constructed tuple.
Tuple expressions without any tuple initializer operands produce the unit tuple.
For other tuple expressions, the first written tuple initializer operand initializes the field `0` and subsequent operands initializes the next highest field. For example, in the tuple expression `('a', 'b', 'c')`, `'a'` initializes the value of the field `0`, `'b'` field `1`, and `'c'` field `2`.
Examples of tuple expressions and their types:
| Expression           | Type         |
| -------------------- | ------------ |
| `()`                 | `()` (unit)  |
| `(0.0, 4.5)`         | `(f64, f64)` |
| `("x".to_string(), )` | `(String, )`  |
| `("a", 4usize, true)`| `(&'static str, usize, bool)` |

Tuple and tuple indexing expressions
Tuple expressions


The Rust Reference › Tuple and tuple indexing expressions › Tuple indexing expressions

```grammar,expressions
TupleIndexingExpression -> Expression `.` TUPLE_INDEX
```
A *tuple indexing expression* accesses fields of tuples and tuple structs.
The syntax for a tuple index expression is an expression, called the *tuple operand*, then a `.`, then finally a tuple index.
The syntax for the *tuple index* is a [decimal literal] with no leading zeros, underscores, or suffix. For example `0` and `2` are valid tuple indices but not `01`, `0_`, nor `0i32`.
The type of the tuple operand must be a [tuple type] or a [tuple struct].
The tuple index must be a name of a field of the type of the tuple operand.
Evaluation of tuple index expressions has no side effects beyond evaluation of its tuple operand. As a [place expression], it evaluates to the location of the field of the tuple operand with the same name as the tuple index.
Examples of tuple indexing expressions:
```rust
// Indexing a tuple
let pair = ("a string", 2);
assert_eq!(pair.1, 2);

// Indexing a tuple struct
let point = Point(1.0, 0.0);
assert_eq!(point.0, 1.0);
assert_eq!(point.1, 0.0);
```
Unlike field access expressions, tuple index expressions can be the function operand of a [call expression] as it cannot be confused with a method call since method names cannot be numbers.
Although arrays and slices also have elements, you must use an [array or slice indexing expression] or a [slice pattern] to access their elements.

Tuple and tuple indexing expressions
Tuple indexing expressions


The Rust Reference › Struct expressions

```grammar,expressions
StructExpression ->
    PathInExpression `{` (StructExprFields | StructBase)? `}`

StructExprFields ->
    StructExprField (`,` StructExprField)* (`,` StructBase | `,`?)

StructExprField ->
    OuterAttribute*
    (
        IDENTIFIER
      | (IDENTIFIER | TUPLE_INDEX) `:` Expression
    )

StructBase -> `..` Expression
```
A *struct expression* creates a struct, enum, or union value. It consists of a path to a [struct], [enum variant], or [union] item followed by the values for the fields of the item.
The following are examples of struct expressions:
```rust
Point {x: 10.0, y: 20.0};
NothingInMe {};
let u = game::User {name: "Joe", age: 35, score: 100_000};
Enum::Variant {};
```
Tuple structs and tuple enum variants are typically instantiated using a call expression referring to the constructor in the value namespace. These are distinct from a struct expression using curly braces referring to the constructor in the type namespace.
```rust
struct Position(i32, i32, i32);
Position(0, 0, 0);  // Typical way of creating a tuple struct.
let c = Position;  // `c` is a function that takes 3 arguments.
let pos = c(8, 6, 7);  // Creates a `Position` value.

enum Version { Triple(i32, i32, i32) };
Version::Triple(0, 0, 0);
let f = Version::Triple;
let ver = f(8, 6, 7);
```
The last segment of the call path cannot refer to a type alias:


The Rust Reference › Struct expressions

```rust
trait Tr { type T; }
impl<T> Tr for T { type T = T; }

struct Tuple();
enum Enum { Tuple() }

// <Unit as Tr>::T(); // causes an error -- `::T` is a type, not a value
<Enum as Tr>::T::Tuple(); // OK
```
----
Unit structs and unit enum variants are typically instantiated using a path expression referring to the constant in the value namespace.
```rust
struct Gamma;
// Gamma unit value, referring to the const in the value namespace.
let a = Gamma;
// Exact same value as `a`, but constructed using a struct expression
// referring to the type namespace.
let b = Gamma {};

enum ColorSpace { Oklch }
let c = ColorSpace::Oklch;
let d = ColorSpace::Oklch {};
```


The Rust Reference › Struct expressions › Field struct expression

A struct expression with fields enclosed in curly braces allows you to specify the value for each individual field in any order. The field name is separated from its value with a colon.
A value of a [union] type can only be created using this syntax, and it must specify exactly one field.

Struct expressions
Field struct expression


The Rust Reference › Struct expressions › Functional update syntax

A struct expression that constructs a value of a struct type can terminate with the syntax `..` followed by an expression to denote a functional update.
The expression following `..` (the base) must have the same struct type as the new struct type being formed.
The entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression.
As with all struct expressions, all of the fields of the struct must be [visible], even those not explicitly named.
```rust
let mut base = Point3d {x: 1, y: 2, z: 3};
let y_ref = &mut base.y;
Point3d {y: 0, z: 10, .. base}; // OK, only base.x is accessed
drop(y_ref);
```
Struct expressions can't be used directly in a [loop] or [if] expression's head, or in the [scrutinee] of an [if let] or [match] expression. However, struct expressions can be used in these situations if they are within another expression, for example inside [parentheses].
The field names can be decimal integer values to specify indices for constructing tuple structs. This can be used with base structs to fill out the remaining indices not specified:
```rust
struct Color(u8, u8, u8);
let c1 = Color(0, 0, 0);  // Typical way of creating a tuple struct.
let c2 = Color{0: 255, 1: 127, 2: 0};  // Specifying fields by index.
let c3 = Color{1: 0, ..c2};  // Fill out all other fields using a base struct.
```

Struct expressions
Functional update syntax


The Rust Reference › Struct expressions › Functional update syntax › Struct field init shorthand

When initializing a data structure (struct, enum, union) with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`. This allows a compact syntax with less duplication. For example:
```rust
Point3d { x: x, y: y_value, z: z };
Point3d { x, y: y_value, z };
```

Struct expressions
Functional update syntax
Struct field init shorthand


The Rust Reference › Call expressions

```grammar,expressions
CallExpression -> Expression `(` CallParams? `)`

CallParams -> Expression ( `,` Expression )* `,`?
```
A *call expression* calls a function. The syntax of a call expression is an expression, called the *function operand*, followed by a parenthesized comma-separated list of expression, called the *argument operands*.
If the function eventually returns, then the expression completes.
For [non-function types], the expression `f(...)` uses the method on one of the following traits based on the function operand:
- [`Fn`] or [`AsyncFn`] --- shared reference.
- [`FnMut`] or [`AsyncFnMut`] --- mutable reference.
- [`FnOnce`] or [`AsyncFnOnce`] --- value.
An automatic borrow will be taken if needed. The function operand will also be [automatically dereferenced] as required.
Some examples of call expressions:
```rust
let three: i32 = add(1i32, 2i32);
let name: &'static str = (|| "Rust")();
```


The Rust Reference › Call expressions › Disambiguating function calls

All function calls are sugar for a more explicit [fully-qualified syntax].
Function calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items.
In the past, the terms "Unambiguous Function Call Syntax", "Universal Function Call Syntax", or "UFCS", have been used in documentation, issues, RFCs, and other community writings. However, these terms lack descriptive power and potentially confuse the issue at hand. We mention them here for searchability's sake.
Several situations often occur which result in ambiguities about the receiver or referent of method or associated function calls. These situations may include:
* Multiple in-scope traits define methods with the same name for the same types
* Auto-`deref` is undesirable; for example, distinguishing between methods on a smart pointer itself and the pointer's referent
* Methods which take no arguments, like [`default()`], and return properties of a type, like [`size_of()`]
To resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits.
For example,

Call expressions
Disambiguating function calls


The Rust Reference › Call expressions › Disambiguating function calls

```rust
trait Pretty {
    fn print(&self);
}

trait Ugly {
    fn print(&self);
}

struct Foo;
impl Pretty for Foo {
    fn print(&self) {}
}

struct Bar;
impl Pretty for Bar {
    fn print(&self) {}
}
impl Ugly for Bar {
    fn print(&self) {}
}

fn main() {
    let f = Foo;
    let b = Bar;

    // we can do this because we only have one item called `print` for `Foo`s
    f.print();
    // more explicit, and, in the case of `Foo`, not necessary
    Foo::print(&f);
    // if you're not into the whole brevity thing
    <Foo as Pretty>::print(&f);

    // b.print(); // Error: multiple 'print' found
    // Bar::print(&b); // Still an error: multiple `print` found

    // necessary because of in-scope items defining `print`
    <Bar as Pretty>::print(&b);
}
```
Refer to [RFC 132] for further details and motivations.


The Rust Reference › Method-call expressions

```grammar,expressions
MethodCallExpression -> Expression `.` PathExprSegment `(`CallParams? `)`
```
A _method call_ consists of an expression (the *receiver*) followed by a single dot, an expression path segment, and a parenthesized expression-list.
Method calls are resolved to associated [methods] on specific traits, either statically dispatching to a method if the exact `self`-type of the left-hand-side is known, or dynamically dispatching if the left-hand-side expression is an indirect trait object.
```rust
let pi: Result<f32, _> = "3.14".parse();
let log_pi = pi.unwrap_or(1.0).log(2.72);
```
When looking up a method call, the receiver may be automatically dereferenced or borrowed in order to call a method. This requires a more complex lookup process than for other functions, since there may be a number of possible methods to call. The following procedure is used:
The first step is to build a list of candidate receiver types. Obtain these by repeatedly dereferencing the receiver expression's type, adding each type encountered to the list, then finally attempting an array [unsized coercion] at the end, and adding the result type if that is successful.
Then, for each candidate `T`, add `&T` and `&mut T` to the list immediately after `T`.


The Rust Reference › Method-call expressions

For instance, if the receiver has type `Box<[i32;2]>`, then the candidate types will be `Box<[i32;2]>`, `&Box<[i32;2]>`, `&mut Box<[i32;2]>`, `[i32; 2]` (by dereferencing), `&[i32; 2]`, `&mut [i32; 2]`, `[i32]` (by unsized coercion), `&[i32]`, and finally `&mut [i32]`.
Then, for each candidate type `T`, search for a [visible] method with a receiver of that type in the following places:
1. `T`'s inherent methods (methods implemented directly on `T`).
1. Any of the methods provided by a [visible] trait implemented by `T`. If `T` is a type parameter, methods provided by trait bounds on `T` are looked up first. Then all remaining methods in scope are looked up.
The lookup is done for each type in order, which can occasionally lead to surprising results. The below code will print "In trait impl!", because `&self` methods are looked up first, the trait method is found before the struct's `&mut self` method is found.
```rust
struct Foo {}

trait Bar {
  fn bar(&self);
}

impl Foo {
  fn bar(&mut self) {
    println!("In struct impl!")
  }
}

impl Bar for Foo {
  fn bar(&self) {
    println!("In trait impl!")
  }
}

fn main() {
  let mut f = Foo{};
  f.bar();
}
```
If this results in multiple possible candidates, then it is an error, and the receiver must be converted to an appropriate receiver type to make the method call.


The Rust Reference › Method-call expressions

This process does not take into account the mutability or lifetime of the receiver, or whether a method is `unsafe`. Once a method is looked up, if it can't be called for one (or more) of those reasons, the result is a compiler error.
If a step is reached where there is more than one possible method, such as where generic methods or traits are considered the same, then it is a compiler error. These cases require a [disambiguating function call syntax] for method and function invocation.
[!EDITION-2021]
Before the 2021 edition, during the search for visible methods, if the candidate receiver type is an [array type], methods provided by the standard library [`IntoIterator`] trait are ignored.
The edition used for this purpose is determined by the token representing the method name.
This special case may be removed in the future.
For [trait objects], if there is an inherent method of the same name as a trait method, it will give a compiler error when trying to call the method in a method call expression. Instead, you can call the method using [disambiguating function call syntax], in which case it calls the trait method, not the inherent method. There is no way to call the inherent method. Just don't define inherent methods on trait objects with the same name as a trait method and you'll be fine.


The Rust Reference › Field access expressions

```grammar,expressions
FieldExpression -> Expression `.` IDENTIFIER
```
A *field expression* is a [place expression] that evaluates to the location of a field of a [struct] or [union].
When the operand is [mutable], the field expression is also mutable.
The syntax for a field expression is an expression, called the *container operand*, then a `.`, and finally an [identifier].
Field expressions cannot be followed by a parenthetical comma-separated list of expressions, as that is instead parsed as a [method call expression]. That is, they cannot be the function operand of a [call expression].
Wrap the field expression in a [parenthesized expression] to use it in a call expression.
```rust
let holds_callable = HoldsCallable { callable: || () };

// Invalid: Parsed as calling the method "callable"
// holds_callable.callable();

// Valid
(holds_callable.callable)();
```
Examples:
```rust,ignore
mystruct.myfield;
foo().x;
(Struct {a: 10, b: 20}).a;
(mystruct.function_field)() // Call expression containing a field expression
```


The Rust Reference › Field access expressions › Automatic dereferencing

If the type of the container operand implements [`Deref`] or `DerefMut` depending on whether the operand is [mutable], it is *automatically dereferenced* as many times as necessary to make the field access possible. This process is also called *autoderef* for short.

Field access expressions
Automatic dereferencing


The Rust Reference › Field access expressions › Borrowing

The fields of a struct or a reference to a struct are treated as separate entities when borrowing. If the struct does not implement [`Drop`] and is stored in a local variable, this also applies to moving out of each of its fields. This also does not apply if automatic dereferencing is done through user-defined types other than [`Box`].
```rust
struct A { f1: String, f2: String, f3: String }
let mut x: A;
let a: &mut String = &mut x.f1; // x.f1 borrowed mutably
let b: &String = &x.f2;         // x.f2 borrowed immutably
let c: &String = &x.f2;         // Can borrow again
let d: String = x.f3;           // Move out of x.f3
```


The Rust Reference › Closure expressions

```grammar,expressions
ClosureExpression ->
    `async`?[^cl-async-edition]
    `move`?
    ( `||` | `|` ClosureParameters? `|` )
    (Expression | `->` TypeNoBounds BlockExpression)

ClosureParameters -> ClosureParam (`,` ClosureParam)* `,`?

ClosureParam -> OuterAttribute* PatternNoTopAlt ( `:` Type )?
```
[^cl-async-edition]: The `async` qualifier is not allowed in the 2015 edition.
A *closure expression*, also known as a lambda expression or a lambda, defines a [closure type] and evaluates to a value of that type. The syntax for a closure expression is an optional `async` keyword, an optional `move` keyword, then a pipe-symbol-delimited (`|`) comma-separated list of [patterns], called the *closure parameters* each optionally followed by a `:` and a type, then an optional `->` and type, called the *return type*, and then an expression, called the *closure body operand*.
The optional type after each pattern is a type annotation for the pattern.
If there is a return type, the closure body must be a [block].
A closure expression denotes a function that maps a list of parameters onto the expression that follows the parameters. Just like a [`let` binding], the closure parameters are irrefutable [patterns], whose type annotation is optional and will be inferred from context if not given.
Each closure expression has a unique, anonymous type.
Significantly, closure expressions _capture their environment_, which regular [function definitions] do not.
Without the `move` keyword, the closure expression infers how it captures each variable from its environment, preferring to capture by shared reference, effectively borrowing all outer variables mentioned inside the closure's body.


The Rust Reference › Closure expressions

If needed the compiler will infer that instead mutable references should be taken, or that the values should be moved or copied (depending on their type) from the environment.
A closure can be forced to capture its environment by copying or moving values by prefixing it with the `move` keyword. This is often used to ensure that the closure's lifetime is `'static`.


The Rust Reference › Closure expressions › Closure trait implementations

Which traits the closure type implements depends on how variables are captured, the types of the captured variables, and the presence of `async`. See the [call traits and coercions] chapter for how and when a closure implements `Fn`, `FnMut`, and `FnOnce`. The closure type implements [`Send`] and [`Sync`] if the type of every captured variable also implements the trait.

Closure expressions
Closure trait implementations


The Rust Reference › Closure expressions › Async closures

Closures marked with the `async` keyword indicate that they are asynchronous in an analogous way to an async function.
Calling the async closure does not perform any work, but instead evaluates to a value that implements [`Future`] that corresponds to the computation of the body of the closure.
```rust
async fn takes_async_callback(f: impl AsyncFn(u64)) {
    f(0).await;
    f(1).await;
}

async fn example() {
    takes_async_callback(async |i| {
        core::future::ready(i).await;
        println!("done with {i}.");
    }).await;
}
```
[!EDITION-2018]
Async closures are only available beginning with Rust 2018.


The Rust Reference › Closure expressions › Example

In this example, we define a function `ten_times` that takes a higher-order function argument, and we then call it with a closure expression as an argument, followed by a closure expression that moves values from its environment.
```rust
fn ten_times<F>(f: F) where F: Fn(i32) {
    for index in 0..10 {
        f(index);
    }
}

ten_times(|j| println!("hello, {}", j));
// With type annotations
ten_times(|j: i32| -> () { println!("hello, {}", j) });

let word = "konnichiwa".to_owned();
ten_times(move |j| println!("{}, {}", word, j));
```


The Rust Reference › Closure expressions › Attributes on closure parameters

Attributes on closure parameters follow the same rules and restrictions as [regular function parameters].

Closure expressions
Attributes on closure parameters


The Rust Reference › Loops and other breakable expressions

```grammar,expressions
LoopExpression ->
    LoopLabel? (
        InfiniteLoopExpression
      | PredicateLoopExpression
      | IteratorLoopExpression
      | LabelBlockExpression
    )
```
Rust supports four loop expressions:
*   A `loop` expression denotes an infinite loop.
*   A `while` expression loops until a predicate is false.
*   A `for` expression extracts values from an iterator, looping until the iterator is empty.
*   A labeled block expression runs a loop exactly once, but allows exiting the loop early with `break`.
All four types of loop support `break` expressions, and labels.
All except labeled block expressions support `continue` expressions.
Only `loop` and labeled block expressions support evaluation to non-trivial values.


The Rust Reference › Loops and other breakable expressions › Infinite loops

```grammar,expressions
InfiniteLoopExpression -> `loop` BlockExpression
```
A `loop` expression repeats execution of its body continuously: `loop { println!("I live."); }`.
A `loop` expression without an associated `break` expression is [diverging] and has type [`!`].
A `loop` expression containing associated `break` expression(s) may terminate, and must have type compatible with the value of the `break` expression(s).

Loops and other breakable expressions
Infinite loops


The Rust Reference › Loops and other breakable expressions › Predicate loops

```grammar,expressions
PredicateLoopExpression -> `while` Conditions BlockExpression
```
A `while` loop expression allows repeating the evaluation of a block while a set of conditions remain true.
Condition operands must be either an [Expression] with a [boolean type] or a conditional `let` match. If all of the condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, then the loop body block executes.
After the loop body successfully executes, the condition operands are re-evaluated to determine if the body should be executed again.
If any condition operand evaluates to `false` or any `let` pattern does not match its scrutinee, the body is not executed and execution continues after the `while` expression.
A `while` expression evaluates to `()`.
An example:
```rust
let mut i = 0;

while i < 10 {
    println!("hello");
    i = i + 1;
}
```

Loops and other breakable expressions
Predicate loops


The Rust Reference › Loops and other breakable expressions › Predicate loops › `while let` patterns

`let` patterns in a `while` condition allow binding new variables into scope when the pattern matches successfully. The following examples illustrate bindings using `let` patterns:
```rust
let mut x = vec![1, 2, 3];

while let Some(y) = x.pop() {
    println!("y = {}", y);
}

while let _ = 5 {
    println!("Irrefutable patterns are always true");
    break;
}
```
A `while let` loop is equivalent to a `loop` expression containing a [`match` expression] as follows.
```rust,ignore
'label: while let PATS = EXPR {
    /* loop body */
}
```
is equivalent to
```rust,ignore
'label: loop {
    match EXPR {
        PATS => { /* loop body */ },
        _ => break,
    }
}
```
Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:
```rust
let mut vals = vec![2, 3, 1, 2, 2];
while let Some(v @ 1) | Some(v @ 2) = vals.pop() {
    // Prints 2, 2, then 1
    println!("{}", v);
}
```

Loops and other breakable expressions
Predicate loops
`while let` patterns


The Rust Reference › Loops and other breakable expressions › Predicate loops › `while` condition chains

Multiple condition operands can be separated with `&&`. These have the same semantics and restrictions as [`if` condition chains].
The following is an example of chaining multiple expressions, mixing `let` bindings and boolean expressions, and with expressions able to reference pattern bindings from previous expressions:
```rust
fn main() {
    let outer_opt = Some(Some(1i32));

    while let Some(inner_opt) = outer_opt
        && let Some(number) = inner_opt
        && number == 1
    {
        println!("Peek a boo");
        break;
    }
}
```

Loops and other breakable expressions
Predicate loops
`while` condition chains


The Rust Reference › Loops and other breakable expressions › Iterator loops

```grammar,expressions
IteratorLoopExpression ->
    `for` Pattern `in` Expression _except [StructExpression]_ BlockExpression
```
A `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`.
If the iterator yields a value, that value is matched against the irrefutable pattern, the body of the loop is executed, and then control returns to the head of the `for` loop. If the iterator is empty, the `for` expression completes.
An example of a `for` loop over the contents of an array:
```rust
let v = &["apples", "cake", "coffee"];

for text in v {
    println!("I like {}.", text);
}
```
An example of a for loop over a series of integers:
```rust
let mut sum = 0;
for n in 1..11 {
    sum += n;
}
assert_eq!(sum, 55);
```
A `for` loop is equivalent to a `loop` expression containing a [`match` expression] as follows:
```rust,ignore
'label: for PATTERN in iter_expr {
    /* loop body */
}
```
is equivalent to
```rust,ignore
{
    let result = match IntoIterator::into_iter(iter_expr) {
        mut iter => 'label: loop {
            let mut next;
            match Iterator::next(&mut iter) {
                Option::Some(val) => next = val,
                Option::None => break,
            };
            let PATTERN = next;
            let () = { /* loop body */ };
        },
    };
    result
}
```
`IntoIterator`, `Iterator`, and `Option` are always the standard library items here, not whatever those names resolve to in the current scope.
The variable names `next`, `iter`, and `val` are for exposition only, they do not actually have names the user can type.

Loops and other breakable expressions
Iterator loops


The Rust Reference › Loops and other breakable expressions › Iterator loops

The outer `match` is used to ensure that any [temporary values] in `iter_expr` don't get dropped before the loop is finished. `next` is declared before being assigned because it results in types being inferred correctly more often.


The Rust Reference › Loops and other breakable expressions › Loop labels

```grammar,expressions
LoopLabel -> LIFETIME_OR_LABEL `:`
```
A loop expression may optionally have a _label_. The label is written as a lifetime preceding the loop expression, as in `'foo: loop { break 'foo; }`, `'bar: while false {}`, `'humbug: for _ in 0..0 {}`.
If a label is present, then labeled `break` and `continue` expressions nested within this loop may exit out of this loop or return control to its head. See break expressions and continue expressions.
Labels follow the hygiene and shadowing rules of local variables. For example, this code will print "outer loop":
```rust
'a: loop {
    'a: loop {
        break 'a;
    }
    print!("outer loop");
    break 'a;
}
```
`'_` is not a valid loop label.

Loops and other breakable expressions
Loop labels


The Rust Reference › Loops and other breakable expressions › `break` expressions

```grammar,expressions
BreakExpression -> `break` LIFETIME_OR_LABEL? Expression?
```
When `break` is encountered, execution of the associated loop body is immediately terminated, for example:
```rust
let mut last = 0;
for x in 1..100 {
    if x > 12 {
        break;
    }
    last = x;
}
assert_eq!(last, 12);
```
A `break` expression is [diverging] and has a type of [`!`].
A `break` expression is normally associated with the innermost `loop`, `for` or `while` loop enclosing the `break` expression, but a label can be used to specify which enclosing loop is affected. Example:
```rust
'outer: loop {
    while true {
        break 'outer;
    }
}
```
A `break` expression is only permitted in the body of a loop, and has one of the forms `break`, `break 'label` or (see below) `break EXPR` or `break 'label EXPR`.
In a `loop` with break expressions or a [labeled block expression], a `break` without an expression is equivalent to `break ()`.

Loops and other breakable expressions
`break` expressions


The Rust Reference › Loops and other breakable expressions › Labeled block expressions

```grammar,expressions
LabelBlockExpression -> BlockExpression
```
Labeled block expressions are exactly like block expressions, except that they allow using `break` expressions within the block.
Unlike loops, `break` expressions within a labeled block expression *must* have a label (i.e. the label is not optional).
Similarly, labeled block expressions *must* begin with a label.
```rust
let result = 'block: {
    do_thing();
    if condition_not_met() {
        break 'block 1;
    }
    do_next_thing();
    if condition_not_met() {
        break 'block 2;
    }
    do_last_thing();
    3
};
```
The type of a labeled block expression is the [least upper bound] of all of the break operands and the final operand. If the final operand is omitted, the type of the final operand defaults to the [unit type], unless the block diverges, in which case it is the [never type].
```rust
fn example(condition: bool) {
    let s = String::from("owned");

    let _: &str = 'block: {
        if condition {
            break 'block &s;  // &String coerced to &str via Deref
        }
        break 'block "literal";  // &'static str coerced to &str
    };
}
```

Loops and other breakable expressions
Labeled block expressions


The Rust Reference › Loops and other breakable expressions › `continue` expressions

```grammar,expressions
ContinueExpression -> `continue` LIFETIME_OR_LABEL?
```
When `continue` is encountered, the current iteration of the associated loop body is immediately terminated, returning control to the loop *head*.
A `continue` expression is [diverging] and has a type of [`!`].
In the case of a `while` loop, the head is the conditional operands controlling the loop.
In the case of a `for` loop, the head is the call-expression controlling the loop.
Like `break`, `continue` is normally associated with the innermost enclosing loop, but `continue 'label` may be used to specify the loop affected.
A `continue` expression is only permitted in the body of a loop.

Loops and other breakable expressions
`continue` expressions


The Rust Reference › Loops and other breakable expressions › `break` and loop values

When associated with a `loop`, a break expression may be used to return a value from that loop, via one of the forms `break EXPR` or `break 'label EXPR`, where `EXPR` is an expression whose result is returned from the `loop`. For example:
```rust
let (mut a, mut b) = (1, 1);
let result = loop {
    if b > 10 {
        break b;
    }
    let c = a + b;
    a = b;
    b = c;
};
// first number in Fibonacci sequence over 10:
assert_eq!(result, 13);
```
The type of a `loop` with associated `break` expressions is the [least upper bound] of all of the break operands.
```rust
fn example(condition: bool) {
    let s = String::from("owned");

    let _: &str = loop {
        if condition {
            break &s; // &String coerced to &str via Deref
        }
        break "literal"; // &'static str coerced to &str
    };
}
```
A `loop` with associated `break` expressions does not [diverge] if any of the break operands do not diverge. If all of the `break` operands diverge, then the `loop` expression also diverges.
```rust
fn diverging_loop_with_break(condition: bool) -> ! {
    // This loop is diverging because all `break` operands are diverging.
    loop {
        if condition {
            break loop {};
        } else {
            break panic!();
        }
    }
}
```

Loops and other breakable expressions
`break` and loop values


The Rust Reference › Loops and other breakable expressions › `break` and loop values

```rust,compile_fail,E0308
fn loop_with_non_diverging_break(condition: bool) -> ! {
    // The type of this loop is i32 even though one of the breaks is
    // diverging.
    loop {
        if condition {
            break loop {};
        } else {
            break 123i32;
        }
    } // ERROR: expected `!`, found `i32`
}
```


The Rust Reference › Range expressions

```grammar,expressions
RangeExpression ->
      RangeExpr
    | RangeFromExpr
    | RangeToExpr
    | RangeFullExpr
    | RangeInclusiveExpr
    | RangeToInclusiveExpr

RangeExpr -> Expression `..` Expression

RangeFromExpr -> Expression `..`

RangeToExpr -> `..` Expression

RangeFullExpr -> `..`

RangeInclusiveExpr -> Expression `..=` Expression

RangeToInclusiveExpr -> `..=` Expression
```
The `..` and `..=` operators will construct an object of one of the `std::ops::Range` (or `core::ops::Range`) variants, according to the following table:
| Production             | Syntax        | Type                         | Range                 |
|------------------------|---------------|------------------------------|-----------------------|
| [RangeExpr]            | start`..`end  | [std::ops::Range]            | start ≤ x < end |
| [RangeFromExpr]        | start`..`     | [std::ops::RangeFrom]        | start ≤ x          |
| [RangeToExpr]          | `..`end       | [std::ops::RangeTo]          |            x < end |
| [RangeFullExpr]        | `..`          | [std::ops::RangeFull]        |            -          |
| [RangeInclusiveExpr]   | start`..=`end | [std::ops::RangeInclusive]   | start ≤ x ≤ end |
| [RangeToInclusiveExpr] | `..=`end      | [std::ops::RangeToInclusive] |            x ≤ end |
Examples:


The Rust Reference › Range expressions

```rust
1..2;   // std::ops::Range
3..;    // std::ops::RangeFrom
..4;    // std::ops::RangeTo
..;     // std::ops::RangeFull
5..=6;  // std::ops::RangeInclusive
..=7;   // std::ops::RangeToInclusive
```
The following expressions are equivalent.
```rust
let x = std::ops::Range {start: 0, end: 10};
let y = 0..10;

assert_eq!(x, y);
```
Ranges can be used in `for` loops:
```rust
for i in 1..11 {
    println!("{}", i);
}
```


The Rust Reference › `if` expressions

```grammar,expressions
IfExpression ->
    `if` Conditions BlockExpressionNoInnerAttributes
    (`else` ( BlockExpressionNoInnerAttributes | IfExpression ) )?

Conditions ->
      Expression _except [StructExpression]_
    | LetChain

LetChain -> LetChainCondition ( `&&` LetChainCondition )*

LetChainCondition ->
      Expression _except [ExcludedConditions]_
    | OuterAttribute* `let` Pattern `=` Scrutinee _except [ExcludedConditions]_

@root ExcludedConditions ->
      StructExpression
    | LazyBooleanExpression
    | RangeExpr
    | RangeFromExpr
    | RangeInclusiveExpr
    | AssignmentExpression
    | CompoundAssignmentExpression
```
The syntax of an `if` expression is a sequence of one or more condition operands separated by `&&`, followed by a consequent block, any number of `else if` conditions and blocks, and an optional trailing `else` block.
Condition operands must be either an [Expression] with a [boolean type] or a conditional `let` match.
If all of the condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, the consequent block is executed and any subsequent `else if` or `else` block is skipped.
If any condition operand evaluates to `false` or any `let` pattern does not match its scrutinee, the consequent block is skipped and any subsequent `else if` condition is evaluated.
If all `if` and `else if` conditions evaluate to `false` then any `else` block is executed.
An `if` expression evaluates to the same value as the executed block, or `()` if no block is evaluated.
An `if` expression must have the same type in all situations.


The Rust Reference › `if` expressions

```rust
if x == 4 {
    println!("x is four");
} else if x == 3 {
    println!("x is three");
} else {
    println!("x is something else");
}

// `if` can be used as an expression.
let y = if 12 * 15 > 150 {
    "Bigger"
} else {
    "Smaller"
};
assert_eq!(y, "Bigger");
```
An `if` expression [diverges] if either the condition expression diverges or if all arms diverge.
```rust,no_run
fn diverging_condition() -> ! {
    // Diverges because the condition expression diverges
    if loop {} {
        ()
    } else {
        ()
    };
    // The semicolon above is important: The type of the `if` expression is
    // `()`, despite being diverging. When the final body expression is
    // elided, the type of the body is inferred to ! because the function body
    // diverges. Without the semicolon, the `if` would be the tail expression
    // with type `()`, which would fail to match the return type `!`.
}

fn diverging_arms() -> ! {
    // Diverges because all arms diverge
    if true {
        loop {}
    } else {
        loop {}
    }
}
```


The Rust Reference › `if` expressions › `if let` patterns

`let` patterns in an `if` condition allow binding new variables into scope when the pattern matches successfully.
The following examples illustrate bindings using `let` patterns:
```rust
let dish = ("Ham", "Eggs");

// This body will be skipped because the pattern is refuted.
if let ("Bacon", b) = dish {
    println!("Bacon is served with {}", b);
} else {
    // This block is evaluated instead.
    println!("No bacon will be served");
}

// This body will execute.
if let ("Ham", b) = dish {
    println!("Ham is served with {}", b);
}

if let _ = 5 {
    println!("Irrefutable patterns are always true");
}
```
Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in [`match` expressions]:
```rust
enum E {
    X(u8),
    Y(u8),
    Z(u8),
}
let v = E::Y(12);
if let E::X(n) | E::Y(n) = v {
    assert_eq!(n, 12);
}
```


The Rust Reference › `if` expressions › Chains of conditions

Multiple condition operands can be separated with `&&`.
Similar to a `&&` [LazyBooleanExpression], each operand is evaluated from left-to-right until an operand evaluates as `false` or a `let` match fails, in which case the subsequent operands are not evaluated.
The bindings of each pattern are put into scope to be available for the next condition operand and the consequent block.
The following is an example of chaining multiple expressions, mixing `let` bindings and boolean expressions, and with expressions able to reference pattern bindings from previous expressions:
```rust
fn single() {
    let outer_opt = Some(Some(1i32));

    if let Some(inner_opt) = outer_opt
        && let Some(number) = inner_opt
        && number == 1
    {
        println!("Peek a boo");
    }
}
```
The above is equivalent to the following without using chains of conditions:
```rust
fn nested() {
    let outer_opt = Some(Some(1i32));

    if let Some(inner_opt) = outer_opt {
        if let Some(number) = inner_opt {
            if number == 1 {
                println!("Peek a boo");
            }
        }
    }
}
```
If any condition operand is a `let` pattern, then none of the condition operands can be a `||` lazy boolean operator expression due to ambiguity and precedence with the `let` scrutinee.
If a `||` expression is needed, then parentheses can be used. For example:
```rust
if let Some(x) = foo
    // Parentheses are required here.
    && (condition1 || condition2)
{}
```
[!EDITION-2024]
Before the 2024 edition, let chains are not supported. That is, the [LetChain] grammar is not allowed in an `if` expression.


The Rust Reference › `match` expressions

```grammar,expressions
MatchExpression ->
    `match` Scrutinee `{`
        InnerAttribute*
        MatchArms?
    `}`

Scrutinee -> Expression _except [StructExpression]_

MatchArms ->
    ( MatchArm `=>` ( ExpressionWithoutBlock `,` | ExpressionWithBlock `,`? ) )*
    MatchArm `=>` Expression `,`?

MatchArm -> OuterAttribute* Pattern MatchArmGuard?

MatchArmGuard -> `if` MatchConditions

MatchConditions ->
     MatchGuardChain
   | Expression

MatchGuardChain -> MatchGuardCondition ( `&&` MatchGuardCondition )*

MatchGuardCondition ->
     Expression _except [ExcludedMatchConditions]_
   | OuterAttribute* `let` Pattern `=` MatchGuardScrutinee

MatchGuardScrutinee -> Expression _except [ExcludedMatchConditions]_

@root ExcludedMatchConditions ->
      LazyBooleanExpression
    | RangeExpr
    | RangeFromExpr
    | RangeInclusiveExpr
    | AssignmentExpression
    | CompoundAssignmentExpression
```
A *`match` expression* branches on a pattern. The exact form of matching that occurs depends on the [pattern].
A `match` expression has a *[scrutinee] expression*, which is the value to compare to the patterns.
The scrutinee expression and the patterns must have the same type.
A `match` behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.
If the scrutinee expression is a [value expression], it is first evaluated into a temporary location, and the resulting value is sequentially compared to the patterns in the arms until a match is found. The first arm with a matching pattern is chosen as the branch target of the `match`, any variables bound by the pattern are assigned to local variables in the arm's block, and control enters the block.


The Rust Reference › `match` expressions

When the scrutinee expression is a [place expression], the match does not allocate a temporary location; however, a by-value binding may copy or move from the memory location. When possible, it is preferable to match on place expressions, as the lifetime of these matches inherits the lifetime of the place expression rather than being restricted to the inside of the match.
An example of a `match` expression:
```rust
let x = 1;

match x {
    1 => println!("one"),
    2 => println!("two"),
    3 => println!("three"),
    4 => println!("four"),
    5 => println!("five"),
    _ => println!("something else"),
}
```
Variables bound within the pattern are scoped to the match guard and the arm's expression.
The [binding mode] (move, copy, or reference) depends on the pattern.
Multiple match patterns may be joined with the `|` operator. Each pattern will be tested in left-to-right sequence until a successful match is found.
```rust
let x = 9;
let message = match x {
    0 | 1  => "not many",
    2 ..= 9 => "a few",
    _      => "lots"
};

assert_eq!(message, "a few");

// Demonstration of pattern match order.
struct S(i32, i32);

match S(1, 2) {
    S(z @ 1, _) | S(_, z @ 2) => assert_eq!(z, 1),
    _ => panic!(),
}
```
The `2..=9` is a [Range Pattern], not a [Range Expression]. Thus, only those types of ranges supported by range patterns can be used in match arms.
Every binding in each `|` separated pattern must appear in all of the patterns in the arm.
Every binding of the same name must have the same type, and have the same binding mode.


The Rust Reference › `match` expressions

The type of the overall `match` expression is the [least upper bound] of the individual match arms.
If there are no match arms, then the `match` expression is [diverging] and the type is [`!`].
```rust
enum Empty {}

fn diverging_match_no_arms() -> ! {
    let e: Empty = make();
    match e {}
}
```
If either the scrutinee expression or all of the match arms diverge, then the entire `match` expression also diverges.


The Rust Reference › `match` expressions › Match guards

Match arms can accept _match guards_ to further refine the criteria for matching a case.
Pattern guards appear after the pattern following the `if` keyword and consist of an [Expression] with a boolean type or a conditional `let` match.
When the pattern matches successfully, the pattern guard is executed. If all of the guard condition operands evaluate to `true` and all of the `let` patterns successfully match their [scrutinee]s, the match arm is successfully matched against and the arm body is executed.
Otherwise, the next pattern, including other matches with the `|` operator in the same arm, is tested.
```rust
let message = match maybe_digit {
    Some(x) if x < 10 => process_digit(x),
    Some(x) => process_other(x),
    None => panic!(),
};
```
Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example:
```rust
let i : Cell<i32> = Cell::new(0);
match 1 {
    1 | _ if { i.set(i.get() + 1); false } => {}
    _ => {}
}
assert_eq!(i.get(), 2);
```
A pattern guard may refer to the variables bound within the pattern they follow.
Before evaluating the guard, a shared reference is taken to the part of the scrutinee the variable matches on. While evaluating the guard, this shared reference is then used when accessing the variable.
Only when the guard evaluates successfully is the value moved, or copied, from the scrutinee into the variable. This allows shared borrows to be used inside guards without moving out of the scrutinee in case guard fails to match.
Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.


The Rust Reference › `match` expressions › Match guards

Guards can use `let` patterns to conditionally match a scrutinee and to bind new variables into scope when the pattern matches successfully.
In this example, the guard condition `let Some(first_char) = name.chars().next()` is evaluated. If the `let` pattern successfully matches (i.e. the string has at least one character), the arm's body is executed. Otherwise, pattern matching continues to the next arm.
The `let` pattern creates a new binding (`first_char`), which can be used alongside the original pattern bindings (`name`) in the arm's body.
```rust
let cmd = Command::Run("example".to_string());

match cmd {
    Command::Run(name) if let Some(first_char) = name.chars().next() => {
        // Both `name` and `first_char` are available here
        println!("Running: {name} (starts with '{first_char}')");
    }
    Command::Run(name) => {
        println!("{name} is empty");
    }
    _ => {}
}
```


The Rust Reference › `match` expressions › Match guard chains

Multiple guard condition operands can be separated with `&&`.
```rust
match foo {
    Some(xs) if let [single] = xs && !already_checked => { dbg!(single); }
    _ => {}
}
```
Similar to a `&&` [LazyBooleanExpression], each operand is evaluated from left-to-right until an operand evaluates as `false` or a `let` match fails, in which case the subsequent operands are not evaluated.
The bindings of each `let` pattern are put into scope to be available for the next condition operand and the match arm body.
If any guard condition operand is a `let` pattern, then none of the condition operands can be a `||` lazy boolean operator expression due to ambiguity and precedence with the `let` scrutinee.
If a `||` expression is needed, then parentheses can be used. For example:
```rust
match foo {
    Some(xs) if let [x] = xs
        // Parentheses are required here.
        && (x < -100 || x > 20) => {}
    _ => {}
}
```


The Rust Reference › `match` expressions › Attributes on match arms

Outer attributes are allowed on match arms. The only attributes that have meaning on match arms are [`cfg`] and the [lint check attributes].
[Inner attributes] are allowed directly after the opening brace of the match expression in the same expression contexts as [attributes on block expressions].

`match` expressions
Attributes on match arms


The Rust Reference › `return` expressions

```grammar,expressions
ReturnExpression -> `return` Expression?
```
Return expressions are denoted with the keyword `return`.
Evaluating a `return` expression moves its argument into the designated output location for the current function call, destroys the current function activation frame, and transfers control to the caller frame.
A `return` expression is [diverging] and has a type of [`!`].
An example of a `return` expression:
```rust
fn max(a: i32, b: i32) -> i32 {
    if a > b {
        return a;
    }
    return b;
}
```


The Rust Reference › Await expressions

```grammar,expressions
AwaitExpression -> Expression `.` `await`
```
An `await` expression is a syntactic construct for suspending a computation provided by an implementation of `std::future::IntoFuture` until the given future is ready to produce a value.
The syntax for an await expression is an expression with a type that implements the [`IntoFuture`] trait, called the *future operand*, then the token `.`, and then the `await` keyword.
Await expressions are legal only within an [async context], like an [`async fn`], [`async` closure], or [`async` block].
More specifically, an await expression has the following effect.
1. Create a future by calling [`IntoFuture::into_future`] on the future operand.
2. Evaluate the future to a [future] `tmp`;
3. Pin `tmp` using [`Pin::new_unchecked`];
4. This pinned future is then polled by calling the [`Future::poll`] method and passing it the current task context;
5. If the call to `poll` returns [`Poll::Pending`], then the future returns `Poll::Pending`, suspending its state so that, when the surrounding async context is re-polled, execution returns to step 3;
6. Otherwise the call to `poll` must have returned [`Poll::Ready`], in which case the value contained in the [`Poll::Ready`] variant is used as the result of the `await` expression itself.
[!EDITION-2018]
Await expressions are only available beginning with Rust 2018.


The Rust Reference › Await expressions › Task context

The task context refers to the [`Context`] which was supplied to the current [async context] when the async context itself was polled. Because `await` expressions are only legal in an async context, there must be some task context available.


The Rust Reference › Await expressions › Approximate desugaring

Effectively, an await expression is roughly equivalent to the following non-normative desugaring:
```rust,ignore
match operand.into_future() {
    mut pinned => loop {
        let mut pin = unsafe { Pin::new_unchecked(&mut pinned) };
        match Pin::future::poll(Pin::borrow(&mut pin), &mut current_context) {
            Poll::Ready(r) => break r,
            Poll::Pending => yield Poll::Pending,
        }
    }
}
```
where the `yield` pseudo-code returns `Poll::Pending` and, when re-invoked, resumes execution from that point. The variable `current_context` refers to the context taken from the async environment.

Await expressions
Approximate desugaring


The Rust Reference › `_` expressions

```grammar,expressions
UnderscoreExpression -> `_`
```
Underscore expressions, denoted with the symbol `_`, are used to signify a placeholder in a destructuring assignment.
They may only appear in the left-hand side of an assignment.
Note that this is distinct from the wildcard pattern.
Examples of `_` expressions:
```rust
let p = (1, 2);
let mut a = 0;
(_, a) = p;

struct Position {
    x: u32,
    y: u32,
}

Position { x: a, y: _ } = Position{ x: 2, y: 3 };

// unused result, assignment to `_` used to declare intent and remove a warning
_ = 2 + 2;
// triggers unused_must_use warning
// 2 + 2;

// equivalent technique using a wildcard pattern in a let-binding
let _ = 2 + 2;
```


The Rust Reference › Patterns

```grammar,patterns
Pattern -> `|`? PatternNoTopAlt  ( `|` PatternNoTopAlt )*

PatternNoTopAlt ->
      PatternWithoutModernRange
    | ModernRangePattern

PatternWithoutModernRange ->
      LiteralPattern
    | IdentifierPattern
    | WildcardPattern
    | RestPattern
    | ReferencePattern
    | StructPattern
    | TupleStructPattern
    | TuplePattern
    | GroupedPattern
    | SlicePattern
    | PathPattern
    | MacroInvocation
    | ObsoleteRangePattern[^obsolete-range-edition]
```
[^obsolete-range-edition]: The [ObsoleteRangePattern] syntax is semantically invalid in the 2021 edition and beyond.
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.
```rust
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 are used in:
* `let` declarations
* Function and closure parameters
* `match` expressions


The Rust Reference › Patterns

* `if let` expressions
* `while let` expressions
* `for` expressions


The Rust Reference › Patterns › Destructuring

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` 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.
When destructuring a data structure with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.
```rust
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);
    }
};
```


The Rust Reference › Patterns › 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:
```rust
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);
}
```


The Rust Reference › Patterns › Literal patterns

```grammar,patterns
LiteralPattern -> `-`? LiteralExpression
```
_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.
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.
Literal patterns are always refutable.
Examples:
```rust
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"),
    }
}
```


The Rust Reference › Patterns › Identifier patterns

```grammar,patterns
IdentifierPattern -> `ref`? `mut`? IDENTIFIER ( `@` PatternNoTopAlt )?
```
Identifier patterns bind the value they match to a variable in the [value namespace].
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 a `match` 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.
```rust
let mut variable = 10;
fn sum(x: i32, y: i32) -> i32 {
```
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).
```rust
let x = 2;

match x {
    e @ 1 ..= 5 => println!("got a range element {}", e),
    _ => println!("anything"),
}
```
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 the `ref` keyword, or to a mutable reference using `ref mut`. For example:
```rust
match a {
    None => (),
    Some(value) => (),
}

match a {
    None => (),
    Some(ref value) => (),
}
```


The Rust Reference › Patterns › Identifier patterns

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:
```rust,compile_fail
if let Person { name: &person_name, age: 18..=150 } = value { }
```
To make it valid, write the following:
```rust
if let Person { name: ref person_name, age: 18..=150 } = value { }
```
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.
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].


The Rust Reference › Patterns › Identifier patterns

```rust
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 constant `42`.
        other_value => Err(x),
    //  ^^^^^^^^^^^ Parsed as an `IdentifierPattern`.
    }
}

// If `EXPECTED_VALUE` were treated as an `IdentifierPattern` above,
// that pattern would always match, making the function always return
// `Ok(_) regardless of the input.
assert_eq!(check_value(42), Ok(42));
assert_eq!(check_value(43), Err(43));
```
It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.
Identifier patterns are irrefutable if the `@` subpattern is irrefutable or the subpattern is not specified.


The Rust Reference › Patterns › Identifier patterns › 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` or `ref mut` binding. Example:
```rust
let x: &Option<i32> = &Some(3);
if let Some(y) = x {
    // y was converted to `ref y` and its type is &i32
}
```
*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`, or `mut`, 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 to `ref`.
Mutable references will set the mode to `ref mut` unless the mode is already `ref` in which case it remains `ref`.
If the automatically dereferenced value is still a reference, it is dereferenced and this process repeats.
The binding pattern may only explicitly specify a `ref` or `ref mut` binding mode, or specify mutability with `mut`, when the default binding mode is "move". For example, these are not accepted:
```rust,edition2024,compile_fail
let [mut x] = &[()]; //~ ERROR
let [ref x] = &[()]; //~ ERROR
let [ref mut x] = &mut [()]; //~ ERROR
```

Patterns
Identifier patterns
Binding modes


The Rust Reference › Patterns › Identifier patterns › Binding modes

[!EDITION-2024]
Before the 2024 edition, bindings could explicitly specify a `ref` or `ref mut` binding mode even when the default binding mode was not "move", and they could specify mutability on such bindings with `mut`. In these editions, specifying `mut` on a binding set the binding mode to "move" regardless of the current default binding mode.
Similarly, a reference pattern may only appear when the default binding mode is "move". For example, this is not accepted:
```rust,edition2024,compile_fail
let [&x] = &[&()]; //~ ERROR
```
[!EDITION-2024]
Before the 2024 edition, reference patterns could appear even when the default binding mode was not "move", and had both the effect of matching against the scrutinee and of causing the default binding mode to be reset to "move".
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 of `person`. Trying to use `person` as a whole or `person.name` would result in an error because of *partial move*.
Example:
```rust
// `name` is moved from person and `age` referenced
let Person { name, ref age } = person;
```


The Rust Reference › Patterns › Wildcard pattern

```grammar,patterns
WildcardPattern -> `_`
```
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:
```rust
let (a, _) = (10, x);   // the x is always matched by _

// ignore a function/closure param
let real_part = |a: f64, _: f64| { a };

// ignore a field from a struct
let RGBA{r: red, g: green, b: blue, a: _} = color;

// accept any Some, with any value
if let Some(_) = x {}
```
The wildcard pattern is always irrefutable.


The Rust Reference › Patterns › Rest pattern

```grammar,patterns
RestPattern -> `..`
```
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:


The Rust Reference › Patterns › Rest pattern

```rust
match slice {
    [] => println!("slice is empty"),
    [one] => println!("single element {}", one),
    [head, tail @ ..] => println!("head={} tail={:?}", head, tail),
}

match slice {
    // Ignore everything but the last element, which must be "!".
    [.., "!"] => println!("!!!"),

    // `start` is a slice of everything except the last element, which must be "z".
    [start @ .., "z"] => println!("starts with: {:?}", start),

    // `end` is a slice of everything but the first element, which must be "a".
    ["a", end @ ..] => println!("ends with: {:?}", end),

    // 'whole' is the entire slice and `last` is the final element
    whole @ [.., last] => println!("the last element of {:?} is {}", whole, last),

    rest => println!("{:?}", rest),
}

if let [.., penultimate, _] = slice {
    println!("next to last is {}", penultimate);
}

// The rest pattern may also be used in tuple and tuple
// struct patterns.
match tuple {
    (1, .., y, z) => println!("y={} z={}", y, z),
    (.., 5) => println!("tail must be 5"),
    (..) => println!("matches everything else"),
}
```


The Rust Reference › Patterns › Range patterns

```grammar,patterns
ModernRangePattern ->
      RangeExclusivePattern
    | RangeInclusivePattern
    | RangeFromPattern
    | RangeToExclusivePattern
    | RangeToInclusivePattern

RangeExclusivePattern ->
      RangePatternBound `..` RangePatternBound

RangeInclusivePattern ->
      RangePatternBound `..=` RangePatternBound

RangeFromPattern ->
      RangePatternBound `..`

RangeToExclusivePattern ->
      `..` RangePatternBound

RangeToInclusivePattern ->
      `..=` RangePatternBound

ObsoleteRangePattern ->
    RangePatternBound `...` RangePatternBound

RangePatternBound ->
      LiteralPattern
    | PathExpression
```
*Range patterns* match scalar values within the range defined by their bounds. They comprise a *sigil* (`..` or `..=`) and a bound on one or both sides.
A bound on the left of the sigil is called a *lower bound*. A bound on the right is called an *upper bound*.
The *exclusive range pattern* matches all values from the lower bound up to, but not including the upper bound. It is written as its lower bound, followed by `..`, followed by the upper bound.
For example, a pattern `'m'..'p'` will match only `'m'`, `'n'` and `'o'`, specifically **not** including `'p'`.
The *inclusive range pattern* matches all values from the lower bound up to and including the upper bound. It is written as its lower bound, followed by `..=`, followed by the upper bound.
For example, a pattern `'m'..='p'` will match only the values `'m'`, `'n'`, `'o'`, and `'p'`.
The *from range pattern* matches all values greater than or equal to the lower bound. It is written as its lower bound followed by `..`.


The Rust Reference › Patterns › Range patterns

For example, `1..` will match any integer greater than or equal to 1, such as 1, 9, or 9001, or 9007199254740991 (if it is of an appropriate size), but not 0, and not negative numbers for signed integers.
The *to exclusive range pattern* matches all values less than the upper bound. It is written as `..` followed by the upper bound.
For example, `..10` will match any integer less than 10, such as 9, 1, 0, and for signed integer types, all negative values.
The *to inclusive range pattern* matches all values less than or equal to the upper bound. It is written as `..=` followed by the upper bound.
For example, `..=10` will match any integer less than or equal to 10, such as 10, 1, 0, and for signed integer types, all negative values.
A range pattern must be nonempty; it must span at least one value in the set of possible values for its type. In other words:
* In `a..=b`, a ≤ b must be the case. For example, it is an error to have a range pattern `10..=0`, but `10..=10` is allowed.
* In `a..b`, a < b must be the case. For example, it is an error to have a range pattern `10..0` or `10..10`.
* In `..b`, b must not be the smallest value of its type. For example, it is an error to have a range pattern `..-128i8` or `..f64::NEG_INFINITY`.
A bound is written as one of:


The Rust Reference › Patterns › Range patterns

* A character, byte, integer, or float literal.
* A `-` followed by an integer or float literal.
* A [path].
We syntactically accept more than this for a *[RangePatternBound]*. We later reject the other things semantically.
If a bound is written as a path, after macro resolution, the path must resolve to a constant item of the type `char`, an integer type, or a float type.
The range pattern matches the type of its upper and lower bounds, which must be the same type.
If a bound is a [path], the bound matches the type and has the value of the [constant] the path resolves to.
If a bound is a literal, the bound matches the type and has the value of the corresponding [literal expression].
If a bound is a literal preceded by a `-`, the bound matches the same type as the corresponding [literal expression] and has the value of [negating] the value of the corresponding literal expression.
For float range patterns, the constant may not be a `NaN`.
Examples:


The Rust Reference › Patterns › Range patterns

```rust
let valid_variable = match c {
    'a'..='z' => true,
    'A'..='Z' => true,
    'α'..='ω' => true,
    _ => false,
};

println!("{}", match ph {
    0..7 => "acid",
    7 => "neutral",
    8..=14 => "base",
    _ => unreachable!(),
});

match uint {
    0 => "zero!",
    1.. => "positive number!",
};

// using paths to constants:
println!("{}", match altitude {
    TROPOSPHERE_MIN..=TROPOSPHERE_MAX => "troposphere",
    STRATOSPHERE_MIN..=STRATOSPHERE_MAX => "stratosphere",
    MESOSPHERE_MIN..=MESOSPHERE_MAX => "mesosphere",
    _ => "outer space, maybe",
});

if let size @ binary::MEGA..=binary::GIGA = n_items * bytes_per_item {
    println!("It fits and occupies {} bytes", size);
}

// using qualified paths:
println!("{}", match 0xfacade {
    0 ..= <u8 as MaxValue>::MAX => "fits in a u8",
    0 ..= <u16 as MaxValue>::MAX => "fits in a u16",
    0 ..= <u32 as MaxValue>::MAX => "fits in a u32",
    _ => "too big",
});
```
Range patterns for fix-width integer and `char` 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 Rust Reference › Patterns › Range patterns

The range of values for a `char` type are precisely those ranges containing all Unicode Scalar Values: `'\u{0000}'..='\u{D7FF}'` and `'\u{E000}'..='\u{10FFFF}'`.
[RangeFromPattern] cannot be used as a top-level pattern for subpatterns in slice patterns. For example, the pattern `[1.., _]` is not a valid pattern.
[!EDITION-2021]
Before the 2021 edition, range patterns with both a lower and upper bound may also be written using `...` in place of `..=`, with the same meaning.


The Rust Reference › Patterns › Reference patterns

```grammar,patterns
ReferencePattern -> (`&`|`&&`) `mut`? PatternWithoutModernRange
```
Reference patterns dereference the pointers that are being matched and, thus, borrow them.
For example, these two matches on `x: &i32` are equivalent:
```rust
let int_reference = &3;

let a = match *int_reference { 0 => "zero", _ => "some" };
let b = match int_reference { &0 => "zero", _ => "some" };

assert_eq!(a, b);
```
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.


The Rust Reference › Patterns › Struct patterns

```grammar,patterns
StructPattern ->
    PathInExpression `{`
        StructPatternElements?
    `}`

StructPatternElements ->
      StructPatternFields (`,` | `,` StructPatternEtCetera)?
    | StructPatternEtCetera

StructPatternFields ->
    StructPatternField (`,` StructPatternField)*

StructPatternField ->
    OuterAttribute*
    (
        TUPLE_INDEX `:` Pattern
      | IDENTIFIER `:` Pattern
      | `ref`? `mut`? IDENTIFIER
    )

StructPatternEtCetera -> `..`
```
Struct patterns match struct, enum, and union values that match all criteria defined by its subpatterns. They are also used to destructure a struct, enum, or union value.
On a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of `..`:
```rust
match s {
    Point {x: 10, y: 20} => (),
    Point {y: 10, x: 20} => (),    // order doesn't matter
    Point {x: 10, ..} => (),
    Point {..} => (),
}

match t {
    PointTuple {0: 10, 1: 20} => (),
    PointTuple {1: 10, 0: 20} => (),   // order doesn't matter
    PointTuple {0: 10, ..} => (),
    PointTuple {..} => (),
}

match m {
    Message::Quit => (),
    Message::Move {x: 10, y: 20} => (),
    Message::Move {..} => (),
}
```
If `..` is not used, a struct pattern used to match a struct is required to specify all fields:


The Rust Reference › Patterns › Struct patterns

```rust
match struct_value {
    Struct{a: 10, b: 'X', c: false} => (),
    Struct{a: 10, b: 'X', ref c} => (),
    Struct{a: 10, b: 'X', ref mut c} => (),
    Struct{a: 10, b: 'X', c: _} => (),
    Struct{a: _, b: _, c: _} => (),
}
```
A struct pattern used to match a union must specify exactly one field (see [Pattern matching on unions]).
The [IDENTIFIER] syntax matches any value and binds it to a variable with the same name as the given field. It is a shorthand for `fieldname: fieldname`. The `ref` and `mut` qualifiers can be included with the behavior as described in [patterns.ident.ref].
```rust
let Struct { a, b, c } = struct_value;
```
A struct pattern is refutable if the [PathInExpression] resolves to a constructor of an enum with more than one variant, or one of its subpatterns is refutable.
A struct pattern matches against the struct, union, or enum variant whose constructor is resolved from [PathInExpression] in the [type namespace]. See [patterns.tuple-struct.namespace] for more details.


The Rust Reference › Patterns › Tuple struct patterns

```grammar,patterns
TupleStructPattern -> PathInExpression `(` TupleStructItems? `)`

TupleStructItems -> Pattern ( `,` Pattern )* `,`?
```
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 if the [PathInExpression] resolves to a constructor of an enum with more than one variant, or one of its subpatterns is refutable.
A tuple struct pattern matches against the tuple struct or [tuple-like enum variant] whose constructor is resolved from [PathInExpression] in the [value namespace].
Conversely, a struct pattern for a tuple struct or [tuple-like enum variant], e.g. `S { 0: _ }`, matches against the tuple struct or variant whose constructor is resolved in the [type namespace].


The Rust Reference › Patterns › Tuple struct patterns

```rust,no_run
enum E1 { V(u16) }
enum E2 { V(u32) }

// Import `E1::V` from the type namespace only.
mod _0 {
    const V: () = (); // For namespace masking.
    pub(super) use super::E1::*;
}
use _0::*;

// Import `E2::V` from the value namespace only.
mod _1 {
    struct V {} // For namespace masking.
    pub(super) use super::E2::*;
}
use _1::*;

fn f() {
    // This struct pattern matches against the tuple-like
    // enum variant whose constructor was found in the type
    // namespace.
    let V { 0: ..=u16::MAX } = (loop {}) else { loop {} };
    // This tuple struct pattern matches against the tuple-like
    // enum variant whose constructor was found in the value
    // namespace.
    let V(..=u32::MAX) = (loop {}) else { loop {} };
}
```
The Lang team has made certain decisions, such as in [PR #138458], that raise questions about the desirability of using the value namespace in this way for patterns, as described in [PR #140593]. It might be prudent to not intentionally rely on this nuance in your code.


The Rust Reference › Patterns › Tuple patterns

```grammar,patterns
TuplePattern -> `(` TuplePatternItems? `)`

TuplePatternItems ->
      Pattern `,`
    | RestPattern
    | Pattern (`,` Pattern)+ `,`?
```
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:
```rust
let pair = (10, "ten");
let (a, b) = pair;

assert_eq!(a, 10);
assert_eq!(b, "ten");
```


The Rust Reference › Patterns › Grouped patterns

```grammar,patterns
GroupedPattern -> `(` Pattern `)`
```
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.
```rust
let int_reference = &3;
match int_reference {
    &(0..=5) => (),
    _ => (),
}
```


The Rust Reference › Patterns › Slice patterns

```grammar,patterns
SlicePattern -> `[` SlicePatternItems? `]`

SlicePatternItems -> Pattern (`,` Pattern)* `,`?
```
Slice patterns can match both arrays of fixed size and slices of dynamic size.
```rust
// Fixed size
let arr = [1, 2, 3];
match arr {
    [1, _, _] => "starts with one",
    [a, b, c] => "starts with something else",
};
```
```rust
// Dynamic size
let v = vec![1, 2, 3];
match v[..] {
    [a, b] => { /* this arm will not apply because the length doesn't match */ }
    [a, b, c] => { /* this arm will apply */ }
    _ => { /* this wildcard is required, since the length is not known statically */ }
};
```
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.
Within a slice, a range pattern without both lower and upper bound must be enclosed in parentheses, as in `(a..)`, to clarify it is intended to match against a single slice element. A range pattern with both lower and upper bound, like `a..=b`, is not required to be enclosed in parentheses.


The Rust Reference › Patterns › Path patterns

```grammar,patterns
PathPattern -> PathExpression
```
_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:
* enum variants
* structs
* constants
* associated constants
Qualified path patterns can only refer to associated constants.
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.


The Rust Reference › Patterns › Path patterns › Constant patterns

When a constant `C` of type `T` is used as a pattern, we first check that `T: PartialEq`.
Furthermore we require that the value of `C` *has (recursive) structural equality*, which is defined recursively as follows:
- Integers as well as `str`, `bool` and `char` values always have structural equality.
- Tuples, arrays, and slices have structural equality if all their fields/elements have structural equality. (In particular, `()` and `[]` always have structural equality.)
- References have structural equality if the value they point to has structural equality.
- A value of `struct` or `enum` type has structural equality if its `PartialEq` instance is derived via `#[derive(PartialEq)]`, and all fields (for enums: of the active variant) have structural equality.
- A raw pointer has structural equality if it was defined as a constant integer (and then cast/transmuted).
- A float value has structural equality if it is not a `NaN`.
- Nothing else has structural equality.
In particular, the value of `C` must be known at pattern-building time (which is pre-monomorphization). This means that associated consts that involve generic parameters cannot be used as patterns.
The value of `C` must not contain any references to mutable statics (`static mut` items or interior mutable `static` items) or `extern` statics.
After ensuring all conditions are met, the constant value is translated into a pattern, and now behaves exactly as-if that pattern had been written directly. In particular, it fully participates in exhaustiveness checking. (For raw pointers, constants are the only way to write such patterns. Only `_` is ever considered exhaustive for these types.)

Patterns
Path patterns
Constant patterns


The Rust Reference › Patterns › Or-patterns

_Or-patterns_ are patterns that match on one of two or more sub-patterns (for example `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 of `let`-bindings and function and closure parameters (represented by the [PatternNoTopAlt] production).


The Rust Reference › Patterns › Or-patterns › Static semantics

1. Given a pattern `p | q` at some depth for some arbitrary patterns `p` and `q`, the pattern is considered ill-formed if:
   + the type inferred for `p` does not unify with the type inferred for `q`, or
   + the same set of bindings are not introduced in `p` and `q`, or
   + the type of any two bindings with the same name in `p` and `q` 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.
2. When type checking an expression `match e_s { a_1 => e_1, ... a_n => e_n }`, for each match arm `a_i` which contains a pattern of form `p_i | q_i`, the pattern `p_i | q_i` is considered ill formed if, at the depth `d` where it exists the fragment of `e_s` at depth `d`, the type of the expression fragment does not unify with `p_i | q_i`.
3. With respect to exhaustiveness checking, a pattern `p | q` is considered to cover `p` as well as `q`. For some constructor `c(x, ..)` the distributive law applies such that `c(p | q, ..rest)` covers the same set of value as `c(p, ..rest) | c(q, ..rest)` does. This can be applied recursively until there are no more nested patterns of form `p | 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.


The Rust Reference › Patterns › Or-patterns › Dynamic semantics

1. The dynamic semantics of pattern matching a scrutinee expression `e_s` against a pattern `c(p | q, ..rest)` at depth `d` where `c` is some constructor, `p` and `q` are arbitrary patterns, and `rest` is optionally any remaining potential factors in `c`, is defined as being the same as that of `c(p, ..rest) | c(q, ..rest)`.


The Rust Reference › Patterns › Or-patterns › 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 that `x` is not bound in all patterns. `&A(x) | B(x)` will result in a type mismatch between `x` in the different subpatterns.


The Rust Reference › Types

Every variable, item, and value in a Rust program has a type. The _type_ of a *value* defines the interpretation of the memory holding it and the operations that may be performed on the value.
Built-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types.
User-defined types have limited capabilities.
The list of types is:
* Primitive types:
    * [Boolean] --- `bool`
    * [Numeric] --- integer and float
    * [`char`]
    * [`str`]
    * [Never] --- `!` --- a type with no values
* Sequence types:
    * [Tuple]
    * [Array]
    * [Slice]
* User-defined types:
    * [Struct]
    * [Enum]
    * [Union]
* Function types:
    * [Functions]
    * [Closures]
* Pointer types:
    * [References]
    * [Raw pointers]
    * [Function pointers]
* Trait types:
    * [Trait objects]
    * [Impl trait]


The Rust Reference › Types › Type expressions

```grammar,types
Type ->
      TypeNoBounds
    | ImplTraitType
    | TraitObjectType

TypeNoBounds ->
      ParenthesizedType
    | ImplTraitTypeOneBound
    | TraitObjectTypeOneBound
    | TypePath
    | TupleType
    | NeverType
    | RawPointerType
    | ReferenceType
    | ArrayType
    | SliceType
    | InferredType
    | QualifiedPathInType
    | BareFunctionType
    | MacroInvocation
```
A _type expression_ as defined in the [Type] grammar rule above is the syntax for referring to a type. It may refer to:
* Sequence types ([tuple], [array], [slice]).
* [Type paths] which can reference:
    * Primitive types ([boolean], [numeric], [`char`], [`str`]).
    * Paths to an [item] ([struct], [enum], [union], [type alias], [trait]).
    * [`Self` path] where `Self` is the implementing type.
    * Generic [type parameters].
* Pointer types ([reference], [raw pointer], [function pointer]).
* The [inferred type] which asks the compiler to determine the type.
* [Parentheses] which are used for disambiguation.
* Trait types: [Trait objects] and [impl trait].
* The [never] type.
* [Macros] which expand to a type expression.


The Rust Reference › Types › Type expressions › Parenthesized types

```grammar,types
ParenthesizedType -> `(` Type `)`
```
In some situations the combination of types may be ambiguous. Use parentheses around a type to avoid ambiguity. For example, the `+` operator for [type boundaries] within a [reference type] is unclear where the boundary applies, so the use of parentheses is required. Grammar rules that require this disambiguation use the [TypeNoBounds] rule instead of Type.
```rust
type T<'a> = &'a (dyn Any + Send);
```

Types
Type expressions
Parenthesized types


The Rust Reference › Types › Recursive types

Nominal types — [structs], [enumerations], and [unions] — may be recursive. That is, each `enum` variant or `struct` or `union` field may refer, directly or indirectly, to the enclosing `enum` or `struct` type itself.
Such recursion has restrictions:
* Recursive types must include a nominal type in the recursion (not mere [type aliases], or other structural types such as [arrays] or [tuples]). So `type Rec = &'static [Rec]` is not allowed.
* The size of a recursive type must be finite; in other words the recursive fields of the type must be [pointer types].
An example of a *recursive* type and its use:
```rust
enum List<T> {
    Nil,
    Cons(T, Box<List<T>>)
}

let a: List<i32> = List::Cons(7, Box::new(List::Cons(13, Box::new(List::Nil))));
```


The Rust Reference › Boolean type

```rust
let b: bool = true;
```
The *boolean type* or *bool* is a primitive data type that can take on one of two values, called *true* and *false*.
Values of this type may be created using a [literal expression] using the keywords `true` and `false` corresponding to the value of the same name.
This type is a part of the [language prelude] with the [name] `bool`.
An object with the boolean type has a [size and alignment] of 1 each.
The value false has the bit pattern `0x00` and the value true has the bit pattern `0x01`. It is [undefined behavior] for an object with the boolean type to have any other bit pattern.
The boolean type is the type of many operands in various [expressions]:
* The condition operand in [if expressions] and [while expressions]
* The operands in lazy boolean operator expressions
The boolean type acts similarly to but is not an [enumerated type]. In practice, this mostly means that constructors are not associated to the type (e.g. `bool::true`).
Like all primitives, the boolean type implements the traits `Clone`, `Copy`, `Sized`, `Send`, and `Sync`.
See the standard library docs for library operations.


The Rust Reference › Boolean type › Operations on boolean values

When using certain operator expressions with a boolean type for its operands, they evaluate using the rules of [boolean logic].

Boolean type
Operations on boolean values


The Rust Reference › Boolean type › Operations on boolean values › Logical not

| `b` | `!b` |
|- | - |
| `true` | `false` |
| `false` | `true` |

Boolean type
Operations on boolean values
Logical not


The Rust Reference › Boolean type › Operations on boolean values › Logical or

| `a` | `b` | `a \| b` |
|- | - | - |
| `true` | `true` | `true` |
| `true` | `false` | `true` |
| `false` | `true` | `true` |
| `false` | `false` | `false` |

Boolean type
Operations on boolean values
Logical or


The Rust Reference › Boolean type › Operations on boolean values › Logical and

| `a` | `b` | `a & b` |
|- | - | - |
| `true` | `true` | `true` |
| `true` | `false` | `false` |
| `false` | `true` | `false` |
| `false` | `false` | `false` |

Boolean type
Operations on boolean values
Logical and


The Rust Reference › Boolean type › Operations on boolean values › Logical xor

| `a` | `b` | `a ^ b` |
|- | - | - |
| `true` | `true` | `false` |
| `true` | `false` | `true` |
| `false` | `true` | `true` |
| `false` | `false` | `false` |

Boolean type
Operations on boolean values
Logical xor


The Rust Reference › Boolean type › Operations on boolean values › Comparisons

| `a` | `b` | `a == b` |
|- | - | - |
| `true` | `true` | `true` |
| `true` | `false` | `false` |
| `false` | `true` | `false` |
| `false` | `false` | `true` |
| `a` | `b` | `a > b` |
|- | - | - |
| `true` | `true` | `false` |
| `true` | `false` | `true` |
| `false` | `true` | `false` |
| `false` | `false` | `false` |
* `a != b` is the same as `!(a == b)`
* `a >= b` is the same as `a == b | a > b`
* `a < b` is the same as `!(a >= b)`
* `a <= b` is the same as `a == b | a < b`

Boolean type
Operations on boolean values
Comparisons


The Rust Reference › Boolean type › Bit validity

The single byte of a `bool` is guaranteed to be initialized (in other words, `transmute::<bool, u8>(...)` is always sound -- but since some bit patterns are invalid `bool`s, the inverse is not always sound).


The Rust Reference › Numeric types › Integer types

The unsigned integer types consist of:
Type   | Minimum | Maximum
-------|---------|-------------------
`u8`   | 0       | 28-1
`u16`  | 0       | 216-1
`u32`  | 0       | 232-1
`u64`  | 0       | 264-1
`u128` | 0       | 2128-1
The signed two's complement integer types consist of:
Type   | Minimum            | Maximum
-------|--------------------|-------------------
`i8`   | -(27)   | 27-1
`i16`  | -(215)  | 215-1
`i32`  | -(231)  | 231-1
`i64`  | -(263)  | 263-1
`i128` | -(2127) | 2127-1


The Rust Reference › Numeric types › Floating-point types

The IEEE 754-2008 "binary32" and "binary64" floating-point types are `f32` and `f64`, respectively.


The Rust Reference › Numeric types › Machine-dependent integer types

The `usize` type is an unsigned integer type with the same number of bits as the platform's pointer type. It can represent every memory address in the process.
While a `usize` can represent every *address*, converting a *pointer* to a `usize` is not necessarily a reversible operation. For more information, see the documentation for [type cast expressions], [`std::ptr`], and provenance in particular.
The `isize` type is a signed two's complement integer type with the same number of bits as the platform's pointer type. The theoretical upper bound on object and array size is the maximum `isize` value. This ensures that `isize` can be used to calculate differences between pointers into an object or array and can address every byte within an object along with one byte past the end.
`usize` and `isize` are at least 16-bits wide.
Many pieces of Rust code may assume that pointers, `usize`, and `isize` are either 32-bit or 64-bit. As a consequence, 16-bit pointer support is limited and may require explicit care and acknowledgment from a library to support.

Numeric types
Machine-dependent integer types


The Rust Reference › Numeric types › Bit validity

For every numeric type, `T`, the bit validity of `T` is equivalent to the bit validity of `[u8; size_of::<T>()]`. An uninitialized byte is not a valid `u8`.


The Rust Reference › Character type

The `char` type represents a single [Unicode scalar value] (i.e., a code point that is not a surrogate).
```rust
let c: char = 'a';
let emoji: char = '😀';
let unicode: char = '\u{1F600}';
```
See the standard library docs for information on the impls of the `char` type.
A value of type `char` is represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range. It is immediate [undefined behavior] to create a `char` that falls outside this range.
`char` is guaranteed to have the same size and alignment as `u32` on all platforms.
Every byte of a `char` is guaranteed to be initialized. In other words, `transmute::<char, [u8; size_of::<char>()]>(...)` is always sound -- but since some bit patterns are invalid `char`s, the inverse is not always sound.


The Rust Reference › String slice type

The string slice (`str`) type represents a sequence of characters.
```rust
let greeting1: &str = "Hello, world!";
let greeting2: &str = "你好，世界";
```
See the standard library docs for information on the impls of the `str` type.
A value of type `str` is represented in the same way as `[u8]`, a slice of 8-bit unsigned bytes.
The standard library makes extra assumptions about `str`: methods working on `str` assume and ensure that the data it contains is valid UTF-8. Calling a `str` method with a non-UTF-8 buffer can cause [undefined behavior] now or in the future.
A `str` is a [dynamically sized type]. It can only be instantiated through a pointer type, such as `&str`. The layout of `&str` is the same as the layout of `&[u8]`.


The Rust Reference › Never type

```grammar,types
NeverType -> `!`
```
The never type `!` is a type with no values, representing the result of computations that never complete.
Expressions of type `!` can be coerced into any other type.
The `!` type can **only** appear in function return types presently, indicating it is a diverging function that never returns.
```rust
fn foo() -> ! {
    panic!("This call never returns.");
}
```
```rust
unsafe extern "C" {
    pub safe fn no_return_extern_func() -> !;
}
```


The Rust Reference › Tuple types

```grammar,types
TupleType ->
      `(` `)`
    | `(` ( Type `,` )+ Type? `)`
```
*Tuple types* are a family of structural types[^1] for heterogeneous lists of other types.
The syntax for a tuple type is a parenthesized, comma-separated list of types.
1-ary tuples require a comma after their element type to be disambiguated with a [parenthesized type].
A tuple type has a number of fields equal to the length of the list of types. This number of fields determines the *arity* of the tuple. A tuple with `n` fields is called an *n-ary tuple*. For example, a tuple with 2 fields is a 2-ary tuple.
Fields of tuples are named using increasing numeric names matching their position in the list of types. The first field is `0`. The second field is `1`. And so on. The type of each field is the type of the same position in the tuple's list of types.
For convenience and historical reasons, the tuple type with no fields (`()`) is often called *unit* or *the unit type*. Its one value is also called *unit* or *the unit value*.
Some examples of tuple types:
* `()` (unit)
* `(i32,)` (1-ary tuple)
* `(f64, f64)`
* `(String, i32)`
* `(i32, String)` (different type from the previous example)
* `(i32, f64, Vec<String>, Option<bool>)`
Values of this type are constructed using a [tuple expression]. Furthermore, various expressions will produce the unit value if there is no other meaningful value for it to evaluate to.
Tuple fields can be accessed by either a [tuple index expression] or [pattern matching].


The Rust Reference › Tuple types

[^1]: Structural types are always equivalent if their internal types are equivalent. For a nominal version of tuples, see [tuple structs].


The Rust Reference › Array types

```grammar,types
ArrayType -> `[` Type `;` Expression `]`
```
An array is a fixed-size sequence of `N` elements of type `T`. The array type is written as `[T; N]`.
The size is a [constant expression] that evaluates to a [`usize`].
Examples:
```rust
// A stack-allocated array
let array: [i32; 3] = [1, 2, 3];

// A heap-allocated array, coerced to a slice
let boxed_array: Box<[i32]> = Box::new([1, 2, 3]);
```
All elements of arrays are always initialized, and access to an array is always bounds-checked in safe methods and operators.
The [`Vec<T>`] standard library type provides a heap-allocated resizable array type.