The Rust Reference

## Keyboard shortcuts

Press `←` or `→` to navigate between chapters

Press `S` or `/` to search in the book

Press `?` to show this help

Press `Esc` to hide this help

# Introduction

This book is the primary reference for the Rust programming language.

> Note

> For known bugs and omissions in this book, see our GitHub issues. If you see a case where the compiler behavior and the text here do not agree, file an issue so we can think about which is correct.

## Rust releases

Rust has a new language release every six weeks. The first stable release of the language was Rust 1.0.0, followed by Rust 1.1.0 and so on. Tools (`rustc`, `cargo`, etc.) and documentation (Standard library, this book, etc.) are released with the language release.

The latest release of this book, matching the latest Rust version, can always be found at https://doc.rust-lang.org/reference/. Prior versions can be found by adding the Rust version before the “reference” directory. For example, the Reference for Rust 1.49.0 is located at https://doc.rust-lang.org/1.49.0/reference/.

## What The Reference is not

This book does not serve as an introduction to the language. Background familiarity with the language is assumed. A separate book is available to help acquire such background familiarity.

This book also does not serve as a reference to the standard library included in the language distribution. Those libraries are documented separately by extracting documentation attributes from their source code. Many of the features that one might expect to be language features are library features in Rust, so what you’re looking for may be there, not here.

Similarly, this book does not usually document the specifics of `rustc` as a tool or of Cargo. `rustc` has its own book. Cargo has a book that contains a reference. There are a few pages such as linkage that still describe how `rustc` works.

This book also only serves as a reference to what is available in stable Rust. For unstable features being worked on, see the Unstable Book.

Rust compilers, including `rustc`, will perform optimizations. The reference does not specify what optimizations are allowed or disallowed. Instead, think of the compiled program as a black box. You can only probe by running it, feeding it input and observing its output. Everything that happens that way must conform to what the reference says.

## How to use this book

This book does not assume you are reading this book sequentially. Each chapter generally can be read standalone, but will cross-link to other chapters for facets of the language they refer to, but do not discuss.

There are two main ways to read this document.

The first is to answer a specific question. If you know which chapter answers that question, you can jump to that chapter in the table of contents. Otherwise, you can press `s` or click the magnifying glass on the top bar to search for keywords related to your question. For example, say you wanted to know when a temporary value created in a let statement is dropped. If you didn’t already know that the lifetime of temporaries is defined in the expressions chapter, you could search “temporary let” and the first search result will take you to that section.

The second is to generally improve your knowledge of a facet of the language. In that case, just browse the table of contents until you see something you want to know more about, and just start reading. If a link looks interesting, click it, and read about that section.

That said, there is no wrong way to read this book. Read it however you feel helps you best.

### Conventions

Like all technical books, this book has certain conventions in how it displays information. These conventions are documented here.

- Statements that define a term contain that term in italics. Whenever that term is used outside of that chapter, it is usually a link to the section that has this definition.

  An example term is an example of a term being defined.

- The main text describes the latest stable edition. Differences to previous editions are separated in edition blocks:

  > 2018 Edition differences

  > Before the 2018 edition, the behavior was this. As of the 2018 edition, the behavior is that.

- Notes that contain useful information about the state of the book or point out useful, but mostly out of scope, information are in note blocks.

  > Note

  > This is an example note.

- Example blocks show an example that demonstrates some rule or points out some interesting aspect. Some examples may have hidden lines which can be viewed by clicking the eye icon that appears when hovering or tapping the example.

  > Example

  > This is a code example.

  >     #![allow(unused)]
  >     fn main() {
  >     println!("hello world");
  >     }

- Warnings that show unsound behavior in the language or possibly confusing interactions of language features are in a special warning box.

  > Warning

  > This is an example warning.

- Code snippets inline in the text are inside `<code>` tags.

  Longer code examples are in a syntax highlighted box that has controls for copying, executing, and showing hidden lines in the top right corner.

      // This is a hidden line.
      fn main() {
          println!("This is a code example");
      }

  All examples are written for the latest edition unless otherwise stated.

- The grammar and lexical productions are described in the Notation chapter.

[example.rule.label]

- Rule identifiers appear before each language rule enclosed in square brackets. These identifiers provide a way to refer to and link to a specific rule in the language (e.g.). The rule identifier uses periods to separate sections from most general to most specific (destructors.scope.nesting.function-body for example). On narrow screens, the rule name will collapse to display `[*]`.

  The rule name can be clicked to link to that rule.

  > Warning

  > The organization of the rules is currently in flux. For the time being, these identifier names are not stable between releases, and links to these rules may fail if they are changed. We intend to stabilize these once the organization has settled so that links to the rule names will not break between releases.

- Rules that have associated tests will include a `Tests` link below them (on narrow screens, the link is `[T]`). Clicking the link will pop up a list of tests, which can be clicked to view the test. For example, see input.encoding.utf8.

  Linking rules to tests is an ongoing effort. See the Test summary chapter for an overview.

## Contributing

We welcome contributions of all kinds.

You can contribute to this book by opening an issue or sending a pull request to the Rust Reference repository. If this book does not answer your question, and you think its answer is in scope of it, please do not hesitate to file an issue or ask about it in the `t-lang/doc` stream on Zulip. Knowing what people use this book for the most helps direct our attention to making those sections the best that they can be. And of course, if you see anything that is wrong or is non-normative but not specifically called out as such, please also file an issue.

[notation]

# Notation

[notation.grammar]

## Grammar

[notation.grammar.syntax]

The following notations are used by the Lexer and Syntax grammar snippets:

Notation | Examples | Meaning
--- | --- | ---
CAPITAL | KW_IF, INTEGER_LITERAL | A token produced by the lexer
ItalicCamelCase | LetStatement, Item | A syntactical production
`string` | `x`, `while`, `*` | The exact character(s)
x? | `pub`? | An optional item
x* | OuterAttribute* | 0 or more of x
x+ | MacroMatch+ | 1 or more of x
xa..b | HEX_DIGIT1..6 | a to b repetitions of x
Rule1 Rule2 | `fn` Name Parameters | Sequence of rules in order
| | `u8` | `u16`, Block | Item | Either one or another
[ ] | [`b` `B`] | Any of the characters listed
[ - ] | [`a`-`z`] | Any of the characters in the range
~[ ] | ~[`b` `B`] | Any characters, except those listed
~`string` | ~`\n`, ~`*/` | Any characters, except this sequence
( ) | (`,` Parameter)? | Groups items
U+xxxx | U+0060 | A single unicode character
<text> | <any ASCII char except CR> | An English description of what should be matched
Rule suffix | IDENTIFIER_OR_KEYWORD except `crate` | A modification to the previous rule
// Comment. | // Single line comment. | A comment extending to the end of the line.

Sequences have a higher precedence than `|` alternation.

[notation.grammar.string-tables]

### String table productions

Some rules in the grammar — notably unary operators, binary operators, and keywords — are given in a simplified form: as a listing of printable strings. These cases form a subset of the rules regarding the token rule, and are assumed to be the result of a lexical-analysis phase feeding the parser, driven by a DFA, operating over the disjunction of all such string table entries.

When such a string in `monospace` font occurs inside the grammar, it is an implicit reference to a single member of such a string table production. See tokens for more information.

[notation.grammar.visualizations]

### Grammar visualizations

Below each grammar block is a button to toggle the display of a syntax diagram. A square element is a non-terminal rule, and a rounded rectangle is a terminal.

# Lexical structure

[input]

# Input format

[input.syntax]

Lexer
CHAR → <a Unicode scalar value>

NUL → U+0000

[input.intro]

This chapter describes how a source file is interpreted as a sequence of tokens.

See Crates and source files for a description of how programs are organised into files.

[input.encoding]

## Source encoding

[input.encoding.utf8]
Tests
Tests with this rule:

- tests/ui/macros/not-utf8.rs
- tests/ui/parser/utf16-be-without-bom.rs
- tests/ui/parser/utf16-le-without-bom.rs

Each source file is interpreted as a sequence of Unicode characters encoded in UTF-8.

[input.encoding.invalid]
Tests
Tests with this rule:

- tests/ui/macros/not-utf8.rs

It is an error if the file is not valid UTF-8.

[input.byte-order-mark]
Tests
Tests with this rule:

- tests/ui/codemap_tests/utf8-bom.rs
- tests/ui/json/json-bom-plus-crlf-multifile.rs
- tests/ui/json/json-bom-plus-crlf.rs

## Byte order mark removal

If the first character in the sequence is `U+FEFF` (BYTE ORDER MARK), it is removed.

[input.crlf]
Tests
Tests with this rule:

- tests/ui/json/json-bom-plus-crlf-multifile.rs
- tests/ui/json/json-bom-plus-crlf.rs
- tests/ui/lexer/lexer-crlf-line-endings-string-literal-doc-comment.rs

## CRLF normalization

Each pair of characters `U+000D` (CR) immediately followed by `U+000A` (LF) is replaced by a single `U+000A` (LF). This happens once, not repeatedly, so after the normalization, there can still exist `U+000D` (CR) immediately followed by `U+000A` (LF) in the input (e.g. if the raw input contained “CR CR LF LF”).

Other occurrences of the character `U+000D` (CR) are left in place (they are treated as whitespace).

[input.shebang]
Tests
Tests with this rule:

- tests/ui/parser/shebang/issue-71471-ignore-tidy.rs
- tests/ui/parser/shebang/shebang-comment.rs
- tests/ui/parser/shebang/shebang-empty.rs
- tests/ui/parser/shebang/shebang-must-start-file.rs
- tests/ui/parser/shebang/shebang-space.rs
- tests/ui/parser/shebang/valid-shebang.rs

## Shebang removal

[input.shebang.intro]

If the remaining sequence begins with the characters `#!`, the characters up to and including the first `U+000A` (LF) are removed from the sequence.

For example, the first line of the following file would be ignored:

    #!/usr/bin/env rustx

    fn main() {
        println!("Hello!");
    }

[input.shebang.inner-attribute]
Tests
Tests with this rule:

- tests/ui/parser/shebang/multiline-attrib.rs
- tests/ui/parser/shebang/regular-attrib.rs
- tests/ui/parser/shebang/shebang-and-attrib.rs
- tests/ui/parser/shebang/shebang-doc-comment.rs
- tests/ui/parser/shebang/sneaky-attrib.rs

As an exception, if the `#!` characters are followed (ignoring intervening comments or whitespace) by a `[` token, nothing is removed. This prevents an inner attribute at the start of a source file being removed.

[input.tokenization]

## Tokenization

The resulting sequence of characters is then converted into tokens as described in the remainder of this chapter.

> Note

> The standard library `include!` macro applies the following transformations to the file it reads:

> - Byte order mark removal.
> - CRLF normalization.
> - Shebang removal when invoked in an item context (as opposed to expression or statement contexts).

> The `include_str!` and `include_bytes!` macros do not apply these transformations.

[lex.keywords]

# Keywords

Rust divides keywords into three categories:

- strict
- reserved
- weak

[lex.keywords.strict]

## Strict keywords

[lex.keywords.strict.intro]

These keywords can only be used in their correct contexts. They cannot be used as the names of:

- Items
- Variables and function parameters
- Fields and variants
- Type parameters
- Lifetime parameters or loop labels
- Macros or attributes
- Macro placeholders
- Crates

[lex.keywords.strict.list]

The following keywords are in all editions:

- `_`
- `as`
- `async`
- `await`
- `break`
- `const`
- `continue`
- `crate`
- `dyn`
- `else`
- `enum`
- `extern`
- `false`
- `fn`
- `for`
- `if`
- `impl`
- `in`
- `let`
- `loop`
- `match`
- `mod`
- `move`
- `mut`
- `pub`
- `ref`
- `return`
- `self`
- `Self`
- `static`
- `struct`
- `super`
- `trait`
- `true`
- `type`
- `unsafe`
- `use`
- `where`
- `while`

[lex.keywords.strict.edition2018]

> 2018 Edition differences

> The following keywords were added in the 2018 edition:

> - `async`
> - `await`
> - `dyn`

[lex.keywords.reserved]

## Reserved keywords

[lex.keywords.reserved.intro]

These keywords aren’t used yet, but they are reserved for future use. They have the same restrictions as strict keywords. The reasoning behind this is to make current programs forward compatible with future versions of Rust by forbidding them to use these keywords.

[lex.keywords.reserved.list]

- `abstract`
- `become`
- `box`
- `do`
- `final`
- `gen`
- `macro`
- `override`
- `priv`
- `try`
- `typeof`
- `unsized`
- `virtual`
- `yield`

[lex.keywords.reserved.edition2018]

> 2018 Edition differences

> The `try` keyword was added as a reserved keyword in the 2018 edition.

[lex.keywords.reserved.edition2024]

> 2024 Edition differences

> The `gen` keyword was added as a reserved keyword in the 2024 edition.

[lex.keywords.weak]

## Weak keywords

[lex.keywords.weak.intro]

These keywords have special meaning only in certain contexts. For example, it is possible to declare a variable or method with the name `union`.

- `'static`
- `macro_rules`
- `raw`
- `safe`
- `union`

[lex.keywords.weak.macro_rules]

- `macro_rules` is used to create custom macros.

[lex.keywords.weak.union]

- `union` is used to declare a union and is only a keyword when used in a union declaration.

[lex.keywords.weak.lifetime-static]

- `'static` is used for the static lifetime and cannot be used as a generic lifetime parameter or loop label

      // error[E0262]: invalid lifetime parameter name: `'static`
      fn invalid_lifetime_parameter<'static>(s: &'static str) -> &'static str { s }

[lex.keywords.weak.safe]

- `safe` is used for functions and statics, which has meaning in external blocks.

[lex.keywords.weak.raw]

- `raw` is used for raw borrow operators, and is only a keyword when matching a raw borrow operator form (such as `&raw const expr` or `&raw mut expr`).

[lex.keywords.weak.dyn.edition2018]

> 2018 Edition differences

> In the 2015 edition, `dyn` is a keyword when used in a type position followed by a path that does not start with `::` or `<`, a lifetime, a question mark, a `for` keyword or an opening parenthesis.

> Beginning in the 2018 edition, `dyn` has been promoted to a strict keyword.

[ident]

# Identifiers

[ident.syntax]

Lexer
IDENTIFIER_OR_KEYWORD → ( XID_Start | _ ) XID_Continue*

XID_Start → <`XID_Start` defined by Unicode>

XID_Continue → <`XID_Continue` defined by Unicode>

RAW_IDENTIFIER → r# IDENTIFIER_OR_KEYWORD

NON_KEYWORD_IDENTIFIER → IDENTIFIER_OR_KEYWORDexcept a strict or reserved keyword

IDENTIFIER → NON_KEYWORD_IDENTIFIER | RAW_IDENTIFIER

RESERVED_RAW_IDENTIFIER →
r# ( _ | crate | self | Self | super )not immediately followed by XID_Continue

[ident.unicode]
Tests
Tests with this rule:

- tests/ui-fulldeps/lexer/unicode-version.rs

Identifiers follow the specification in Unicode Standard Annex #31 for Unicode version 17.0, with the additions described below. Some examples of identifiers:

- `foo`
- `_identifier`
- `r#true`
- `Москва`
- `東京`

[ident.profile]

The profile used from UAX #31 is:

- Start := `XID_Start`, plus the underscore character (U+005F)
- Continue := `XID_Continue`
- Medial := empty

> Note

> Identifiers starting with an underscore are typically used to indicate an identifier that is intentionally unused, and will silence the unused warning in `rustc`.

[ident.keyword]

Identifiers may not be a strict or reserved keyword without the `r#` prefix described below in raw identifiers.

[ident.zero-width-chars]

Zero width non-joiner (ZWNJ U+200C) and zero width joiner (ZWJ U+200D) characters are not allowed in identifiers.

[ident.ascii-limitations]

Identifiers are restricted to the ASCII subset of `XID_Start` and `XID_Continue` in the following situations:

- `extern crate` declarations (except the AsClause identifier)
- External crate names referenced in a path
- Module names loaded from the filesystem without a `path` attribute
- `no_mangle` attributed items
- Item names in external blocks

[ident.normalization]
Tests
Tests with this rule:

- tests/ui-fulldeps/lexer/unicode-version.rs

## Normalization

Identifiers are normalized using Normalization Form C (NFC) as defined in Unicode Standard Annex #15. Two identifiers are equal if their NFC forms are equal.

Procedural and declarative macros receive normalized identifiers in their input.

[ident.raw]

## Raw identifiers

[ident.raw.intro]

A raw identifier is like a normal identifier, but prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual identifier.)

[ident.raw.allowed]

Unlike a normal identifier, a raw identifier may be any strict or reserved keyword except the ones listed above for `RAW_IDENTIFIER`.

[ident.raw.reserved]

It is an error to use the RESERVED_RAW_IDENTIFIER token.

[comments]

# Comments

[comments.syntax]

Lexer
LINE_COMMENT →
// ( ~[/ ! LF] | // ) ~LF*
| //

BLOCK_COMMENT →
/*
( ~[* !] | ** | BLOCK_COMMENT_OR_DOC )
( BLOCK_COMMENT_OR_DOC | ~*/ )*
*/
| /**/
| /***/

INNER_LINE_DOC →
//! ~[LF CR]*

INNER_BLOCK_DOC →
/*! ( BLOCK_COMMENT_OR_DOC | ~[*/ CR] )* */

OUTER_LINE_DOC →
/// ( ~/ ~[LF CR]* )?

OUTER_BLOCK_DOC →
/**
( ~* | BLOCK_COMMENT_OR_DOC )
( BLOCK_COMMENT_OR_DOC | ~[*/ CR] )*
*/

BLOCK_COMMENT_OR_DOC →
BLOCK_COMMENT
| OUTER_BLOCK_DOC
| INNER_BLOCK_DOC

[comments.normal]

## Non-doc comments

Comments follow the general C++ style of line (`//`) and block (`/* ... */`) comment forms. Nested block comments are supported.

[comments.normal.tokenization]

Non-doc comments are interpreted as a form of whitespace.

[comments.doc]

## Doc comments

[comments.doc.syntax]

Line doc comments beginning with exactly three slashes (`///`), and block doc comments (`/** ... */`), both outer doc comments, are interpreted as a special syntax for `doc` attributes.

[comments.doc.attributes]

That is, they are equivalent to writing `#[doc="..."]` around the body of the comment, i.e., `/// Foo` turns into `#[doc="Foo"]` and `/** Bar */` turns into `#[doc="Bar"]`. They must therefore appear before something that accepts an outer attribute.

[comments.doc.inner-syntax]

Line comments beginning with `//!` and block comments `/*! ... */` are doc comments that apply to the parent of the comment, rather than the item that follows.

[comments.doc.inner-attributes]

That is, they are equivalent to writing `#![doc="..."]` around the body of the comment. `//!` comments are usually used to document modules that occupy a source file.

[comments.doc.bare-crs]

The character `U+000D` (CR) is not allowed in doc comments.

> Note

> It is conventional for doc comments to contain Markdown, as expected by `rustdoc`. However, the comment syntax does not respect any internal Markdown. `/** `glob = "*/*.rs";` */` terminates the comment at the first `*/`, and the remaining code would cause a syntax error. This slightly limits the content of block doc comments compared to line doc comments.

> Note

> The sequence `U+000D` (CR) immediately followed by `U+000A` (LF) would have been previously transformed into a single `U+000A` (LF).

## Examples

    #![allow(unused)]
    fn main() {
    //! A doc comment that applies to the implicit anonymous module of this crate

    pub mod outer_module {

        //!  - Inner line doc
        //!! - Still an inner line doc (but with a bang at the beginning)

        /*!  - Inner block doc */
        /*!! - Still an inner block doc (but with a bang at the beginning) */

        //   - Only a comment
        ///  - Outer line doc (exactly 3 slashes)
        //// - Only a comment

        /*   - Only a comment */
        /**  - Outer block doc (exactly) 2 asterisks */
        /*** - Only a comment */

        pub mod inner_module {}

        pub mod nested_comments {
            /* In Rust /* we can /* nest comments */ */ */

            // All three types of block comments can contain or be nested inside
            // any other type:

            /*   /* */  /** */  /*! */  */
            /*!  /* */  /** */  /*! */  */
            /**  /* */  /** */  /*! */  */
            pub mod dummy_item {}
        }

        pub mod degenerate_cases {
            // empty inner line doc
            //!

            // empty inner block doc
            /*!*/

            // empty line comment
            //

            // empty outer line doc
            ///

            // empty block comment
            /**/

            pub mod dummy_item {}

            // empty 2-asterisk block isn't a doc block, it is a block comment
            /***/

        }

        /* The next one isn't allowed because outer doc comments
           require an item that will receive the doc */

        /// Where is my item?
      mod boo {}
    }
    }

[lex.whitespace]

# Whitespace

[whitespace.syntax]

Lexer
WHITESPACE →
U+0009 // Horizontal tab, `'\t'`
| U+000A // Line feed, `'\n'`
| U+000B // Vertical tab
| U+000C // Form feed
| U+000D // Carriage return, `'\r'`
| U+0020 // Space, `' '`
| U+0085 // Next line
| U+200E // Left-to-right mark
| U+200F // Right-to-left mark
| U+2028 // Line separator
| U+2029 // Paragraph separator

TAB → U+0009 // Horizontal tab, `'\t'`

LF → U+000A // Line feed, `'\n'`

CR → U+000D // Carriage return, `'\r'`

[lex.whitespace.intro]

Whitespace is any non-empty string containing only characters that have the `Pattern_White_Space` Unicode property.

[lex.whitespace.token-sep]

Rust is a “free-form” language, meaning that all forms of whitespace serve only to separate tokens in the grammar, and have no semantic significance.

[lex.whitespace.replacement]

A Rust program has identical meaning if each whitespace element is replaced with any other legal whitespace element, such as a single space character.

[lex.token]

# Tokens

[lex.token.syntax]

Lexer
Token →
RESERVED_TOKEN
| RAW_IDENTIFIER
| CHAR_LITERAL
| STRING_LITERAL
| RAW_STRING_LITERAL
| BYTE_LITERAL
| BYTE_STRING_LITERAL
| RAW_BYTE_STRING_LITERAL
| C_STRING_LITERAL
| RAW_C_STRING_LITERAL
| FLOAT_LITERAL
| INTEGER_LITERAL
| LIFETIME_TOKEN
| PUNCTUATION
| IDENTIFIER_OR_KEYWORD

[lex.token.intro]

Tokens are primitive productions in the grammar defined by regular (non-recursive) languages. Rust source input can be broken down into the following kinds of tokens:

- Keywords
- Identifiers
- Literals
- Lifetimes
- Punctuation
- Delimiters

Within this documentation’s grammar, “simple” tokens are given in string table production form, and appear in `monospace` font.

[lex.token.literal]

## Literals

Literals are tokens used in literal expressions.

### Examples

#### Characters and strings

| Example | `#` sets1 | Characters | Escapes
--- | --- | --- | --- | ---
Character | `'H'` | 0 | All Unicode | Quote & ASCII & Unicode
String | `"hello"` | 0 | All Unicode | Quote & ASCII & Unicode
Raw string | `r#"hello"#` | <256 | All Unicode | `N/A`
Byte | `b'H'` | 0 | All ASCII | Quote & Byte
Byte string | `b"hello"` | 0 | All ASCII | Quote & Byte
Raw byte string | `br#"hello"#` | <256 | All ASCII | `N/A`
C string | `c"hello"` | 0 | All Unicode | Quote & Byte & Unicode
Raw C string | `cr#"hello"#` | <256 | All Unicode | `N/A`

#### ASCII escapes

| Name
--- | ---
`\x41` | 7-bit character code (exactly 2 hex digits, up to 0x7F)
`\n` | Newline
`\r` | Carriage return
`\t` | Tab
`\\` | Backslash
`\0` | Null

#### Byte escapes

| Name
--- | ---
`\x7F` | 8-bit character code (exactly 2 hex digits)
`\n` | Newline
`\r` | Carriage return
`\t` | Tab
`\\` | Backslash
`\0` | Null

#### Unicode escapes

| Name
--- | ---
`\u{7FFF}` | 24-bit Unicode character code (up to 6 hex digits)

#### Quote escapes

| Name
--- | ---
`\'` | Single quote
`\"` | Double quote

#### Numbers

Number literals2 | Example | Exponentiation
--- | --- | ---
Decimal integer | `98_222` | `N/A`
Hex integer | `0xff` | `N/A`
Octal integer | `0o77` | `N/A`
Binary integer | `0b1111_0000` | `N/A`
Floating-point | `123.0E+77` | `Optional`

[lex.token.literal.suffix]

#### Suffixes

[lex.token.literal.literal.suffix.intro]

A suffix is a sequence of characters following the primary part of a literal (without intervening whitespace), of the same form as a non-raw identifier or keyword.

[lex.token.literal.suffix.syntax]

Lexer
SUFFIX → IDENTIFIER_OR_KEYWORDexcept `_`

SUFFIX_NO_E → SUFFIXnot beginning with `e` or `E`

[lex.token.literal.suffix.validity]

Any kind of literal (string, integer, etc) with any suffix is valid as a token.

A literal token with any suffix can be passed to a macro without producing an error. The macro itself will decide how to interpret such a token and whether to produce an error or not. In particular, the `literal` fragment specifier for by-example macros matches literal tokens with arbitrary suffixes.

    #![allow(unused)]
    fn main() {
    macro_rules! blackhole { ($tt:tt) => () }
    macro_rules! blackhole_lit { ($l:literal) => () }

    blackhole!("string"suffix); // OK
    blackhole_lit!(1suffix); // OK
    }

[lex.token.literal.suffix.parse]

However, suffixes on literal tokens which are interpreted as literal expressions or patterns are restricted. Any suffixes are rejected on non-numeric literal tokens, and numeric literal tokens are accepted only with suffixes from the list below.

Integer | Floating-point
--- | ---
`u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, `isize` | `f32`, `f64`

### Character and string literals

[lex.token.literal.char]

#### Character literals

[lex.token.literal.char.syntax]

Lexer
CHAR_LITERAL →
'
( ~[' \ LF CR TAB] | QUOTE_ESCAPE | ASCII_ESCAPE | UNICODE_ESCAPE )
' SUFFIX?

QUOTE_ESCAPE → \' | \"

ASCII_ESCAPE →
\x OCT_DIGIT HEX_DIGIT
| \n | \r | \t | \\ | \0

UNICODE_ESCAPE →
\u{ ( HEX_DIGIT _* )1..6valid hex char value }​3

[lex.token.literal.char.intro]

A character literal is a single Unicode character enclosed within two `U+0027` (single-quote) characters, with the exception of `U+0027` itself, which must be escaped by a preceding `U+005C` character (`\`).

[lex.token.literal.str]

#### String literals

[lex.token.literal.str.syntax]

Lexer
STRING_LITERAL →
" (
~[" \ CR]
| QUOTE_ESCAPE
| ASCII_ESCAPE
| UNICODE_ESCAPE
| STRING_CONTINUE
)* " SUFFIX?

STRING_CONTINUE → \ LF

[lex.token.literal.str.intro]

A string literal is a sequence of any Unicode characters enclosed within two `U+0022` (double-quote) characters, with the exception of `U+0022` itself, which must be escaped by a preceding `U+005C` character (`\`).

[lex.token.literal.str.linefeed]

Line-breaks, represented by the character `U+000A` (LF), are allowed in string literals. The character `U+000D` (CR) may not appear in a string literal. When an unescaped `U+005C` character (`\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See String continuation escapes for details.

[lex.token.literal.char-escape]

#### Character escapes

[lex.token.literal.char-escape.intro]

Some additional escapes are available in either character or non-raw string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms:

[lex.token.literal.char-escape.ascii]

- A 7-bit code point escape starts with `U+0078` (`x`) and is followed by exactly two hex digits with value up to `0x7F`. It denotes the ASCII character with value equal to the provided hex value. Higher values are not permitted because it is ambiguous whether they mean Unicode code points or byte values.

[lex.token.literal.char-escape.unicode]

- A 24-bit code point escape starts with `U+0075` (`u`) and is followed by up to six hex digits surrounded by braces `U+007B` (`{`) and `U+007D` (`}`). It denotes the Unicode code point equal to the provided hex value. The value must be a valid Unicode scalar value.

[lex.token.literal.char-escape.whitespace]

- A whitespace escape is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the Unicode values `U+000A` (LF), `U+000D` (CR) or `U+0009` (HT) respectively.

[lex.token.literal.char-escape.null]

- The null escape is the character `U+0030` (`0`) and denotes the Unicode value `U+0000` (NUL).

[lex.token.literal.char-escape.slash]

- The backslash escape is the character `U+005C` (`\`) which must be escaped in order to denote itself.

[lex.token.literal.str-raw]

#### Raw string literals

[lex.token.literal.str-raw.syntax]

Lexer
RAW_STRING_LITERAL → r RAW_STRING_CONTENT SUFFIX?

RAW_STRING_CONTENT →
" ( ~CR )* (non-greedy) "
| # RAW_STRING_CONTENT #

[lex.token.literal.str-raw.intro]

Raw string literals do not process any escapes. They start with the character `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`) and a `U+0022` (double-quote) character.

[lex.token.literal.str-raw.body]

The raw string body can contain any sequence of Unicode characters other than `U+000D` (CR). It is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character.

[lex.token.literal.str-raw.content]

All Unicode characters contained in the raw string body represent themselves, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning.

Examples for string literals:

    #![allow(unused)]
    fn main() {
    "foo"; r"foo";                     // foo
    "\"foo\""; r#""foo""#;             // "foo"

    "foo #\"# bar";
    r##"foo #"# bar"##;                // foo #"# bar

    "\x52"; "R"; r"R";                 // R
    "\\x52"; r"\x52";                  // \x52
    }

### Byte and byte string literals

[lex.token.byte]

#### Byte literals

[lex.token.byte.syntax]

Lexer
BYTE_LITERAL →
b' ( ASCII_FOR_CHAR | BYTE_ESCAPE ) ' SUFFIX?

ASCII_FOR_CHAR →
<any ASCII (i.e. 0x00 to 0x7F) except `'`, `\`, LF, CR, or TAB>

BYTE_ESCAPE →
\x HEX_DIGIT HEX_DIGIT
| \n | \r | \t | \\ | \0 | \' | \"

[lex.token.byte.intro]

A byte literal is a single ASCII character (in the `U+0000` to `U+007F` range) or a single escape preceded by the characters `U+0062` (`b`) and `U+0027` (single-quote), and followed by the character `U+0027`. If the character `U+0027` is present within the literal, it must be escaped by a preceding `U+005C` (`\`) character. It is equivalent to a `u8` unsigned 8-bit integer number literal.

[lex.token.str-byte]

#### Byte string literals

[lex.token.str-byte.syntax]

Lexer
BYTE_STRING_LITERAL →
b" ( ASCII_FOR_STRING | BYTE_ESCAPE | STRING_CONTINUE )* " SUFFIX?

ASCII_FOR_STRING →
<any ASCII (i.e 0x00 to 0x7F) except `"`, `\`, or CR>

[lex.token.str-byte.intro]

A non-raw byte string literal is a sequence of ASCII characters and escapes, preceded by the characters `U+0062` (`b`) and `U+0022` (double-quote), and followed by the character `U+0022`. If the character `U+0022` is present within the literal, it must be escaped by a preceding `U+005C` (`\`) character. Alternatively, a byte string literal can be a raw byte string literal, defined below.

[lex.token.str-byte.linefeed]

Line-breaks, represented by the character `U+000A` (LF), are allowed in byte string literals. The character `U+000D` (CR) may not appear in a byte string literal. When an unescaped `U+005C` character (`\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See String continuation escapes for details.

[lex.token.str-byte.escape]

Some additional escapes are available in either byte or non-raw byte string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms:

[lex.token.str-byte.escape-byte]

- A byte escape escape starts with `U+0078` (`x`) and is followed by exactly two hex digits. It denotes the byte equal to the provided hex value.

[lex.token.str-byte.escape-whitespace]

- A whitespace escape is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF), `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.

[lex.token.str-byte.escape-null]

- The null escape is the character `U+0030` (`0`) and denotes the byte value `0x00` (ASCII NUL).

[lex.token.str-byte.escape-slash]

- The backslash escape is the character `U+005C` (`\`) which must be escaped in order to denote its ASCII encoding `0x5C`.

[lex.token.str-byte-raw]

#### Raw byte string literals

[lex.token.str-byte-raw.syntax]

Lexer
RAW_BYTE_STRING_LITERAL →
br RAW_BYTE_STRING_CONTENT SUFFIX?

RAW_BYTE_STRING_CONTENT →
" ASCII_FOR_RAW* (non-greedy) "
| # RAW_BYTE_STRING_CONTENT #

ASCII_FOR_RAW →
<any ASCII (i.e. 0x00 to 0x7F) except CR>

[lex.token.str-byte-raw.intro]

Raw byte string literals do not process any escapes. They start with the character `U+0062` (`b`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character.

[lex.token.str-byte-raw.body]

The raw string body can contain any sequence of ASCII characters other than `U+000D` (CR). It is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character. A raw byte string literal can not contain any non-ASCII byte.

[lex.token.literal.str-byte-raw.content]

All characters contained in the raw string body represent their ASCII encoding, the characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw string literal) or `U+005C` (`\`) do not have any special meaning.

Examples for byte string literals:

    #![allow(unused)]
    fn main() {
    b"foo"; br"foo";                     // foo
    b"\"foo\""; br#""foo""#;             // "foo"

    b"foo #\"# bar";
    br##"foo #"# bar"##;                 // foo #"# bar

    b"\x52"; b"R"; br"R";                // R
    b"\\x52"; br"\x52";                  // \x52
    }

### C string and raw C string literals

[lex.token.str-c]

#### C string literals

[lex.token.str-c.syntax]

Lexer
C_STRING_LITERAL →
c" (
~[" \ CR NUL]
| BYTE_ESCAPEexcept `\0` or `\x00`
| UNICODE_ESCAPEexcept `\u{0}`, `\u{00}`, …, `\u{000000}`
| STRING_CONTINUE
)* " SUFFIX?

[lex.token.str-c.intro]

A C string literal is a sequence of Unicode characters and escapes, preceded by the characters `U+0063` (`c`) and `U+0022` (double-quote), and followed by the character `U+0022`. If the character `U+0022` is present within the literal, it must be escaped by a preceding `U+005C` (`\`) character. Alternatively, a C string literal can be a raw C string literal, defined below.

[lex.token.str-c.null]

C strings are implicitly terminated by byte `0x00`, so the C string literal `c""` is equivalent to manually constructing a `&CStr` from the byte string literal `b"\x00"`. Other than the implicit terminator, byte `0x00` is not permitted within a C string.

[lex.token.str-c.linefeed]

Line-breaks, represented by the character `U+000A` (LF), are allowed in C string literals. The character `U+000D` (CR) may not appear in a C string literal. When an unescaped `U+005C` character (`\`) occurs immediately before a line break, the line break does not appear in the string represented by the token. See String continuation escapes for details.

[lex.token.str-c.escape]

Some additional escapes are available in non-raw C string literals. An escape starts with a `U+005C` (`\`) and continues with one of the following forms:

[lex.token.str-c.escape-byte]

- A byte escape escape starts with `U+0078` (`x`) and is followed by exactly two hex digits. It denotes the byte equal to the provided hex value.

[lex.token.str-c.escape-unicode]

- A 24-bit code point escape starts with `U+0075` (`u`) and is followed by up to six hex digits surrounded by braces `U+007B` (`{`) and `U+007D` (`}`). It denotes the Unicode code point equal to the provided hex value, encoded as UTF-8.

[lex.token.str-c.escape-whitespace]

- A whitespace escape is one of the characters `U+006E` (`n`), `U+0072` (`r`), or `U+0074` (`t`), denoting the bytes values `0x0A` (ASCII LF), `0x0D` (ASCII CR) or `0x09` (ASCII HT) respectively.

[lex.token.str-c.escape-slash]

- The backslash escape is the character `U+005C` (`\`) which must be escaped in order to denote its ASCII encoding `0x5C`.

[lex.token.str-c.char-unicode]

A C string represents bytes with no defined encoding, but a C string literal may contain Unicode characters above `U+007F`. Such characters will be replaced with the bytes of that character’s UTF-8 representation.

The following C string literals are equivalent:

    #![allow(unused)]
    fn main() {
    c"æ";        // LATIN SMALL LETTER AE (U+00E6)
    c"\u{00E6}";
    c"\xC3\xA6";
    }

[lex.token.str-c.edition2021]

> 2021 Edition differences

> C string literals are accepted in the 2021 edition or later. In earlier editions the token `c""` is lexed as `c ""`.

[lex.token.str-c-raw]

#### Raw C string literals

[lex.token.str-c-raw.syntax]

Lexer
RAW_C_STRING_LITERAL →
cr RAW_C_STRING_CONTENT SUFFIX?

RAW_C_STRING_CONTENT →
" ( ~[CR NUL] )* (non-greedy) "
| # RAW_C_STRING_CONTENT #

[lex.token.str-c-raw.intro]

Raw C string literals do not process any escapes. They start with the character `U+0063` (`c`), followed by `U+0072` (`r`), followed by fewer than 256 of the character `U+0023` (`#`), and a `U+0022` (double-quote) character.

[lex.token.str-c-raw.body]

The raw C string body can contain any sequence of Unicode characters other than `U+0000` (NUL) and `U+000D` (CR). It is terminated only by another `U+0022` (double-quote) character, followed by the same number of `U+0023` (`#`) characters that preceded the opening `U+0022` (double-quote) character.

[lex.token.str-c-raw.content]

All characters contained in the raw C string body represent themselves in UTF-8 encoding. The characters `U+0022` (double-quote) (except when followed by at least as many `U+0023` (`#`) characters as were used to start the raw C string literal) or `U+005C` (`\`) do not have any special meaning.

[lex.token.str-c-raw.edition2021]

> 2021 Edition differences

> Raw C string literals are accepted in the 2021 edition or later. In earlier editions the token `cr""` is lexed as `cr ""`, and `cr#""#` is lexed as `cr #""#` (which is non-grammatical).

#### Examples for C string and raw C string literals

    #![allow(unused)]
    fn main() {
    c"foo"; cr"foo";                     // foo
    c"\"foo\""; cr#""foo""#;             // "foo"

    c"foo #\"# bar";
    cr##"foo #"# bar"##;                 // foo #"# bar

    c"\x52"; c"R"; cr"R";                // R
    c"\\x52"; cr"\x52";                  // \x52
    }

[lex.token.literal.num]

### Number literals

A number literal is either an integer literal or a floating-point literal. The grammar for recognizing the two kinds of literals is mixed.

[lex.token.literal.int]

#### Integer literals

[lex.token.literal.int.syntax]

Lexer
INTEGER_LITERAL →
( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL | DEC_LITERAL ) SUFFIX_NO_E?

DEC_LITERAL → DEC_DIGIT ( DEC_DIGIT | _ )*

BIN_LITERAL → 0b _* BIN_DIGIT ( BIN_DIGIT | _ )*

OCT_LITERAL → 0o _* OCT_DIGIT ( OCT_DIGIT | _ )*

HEX_LITERAL → 0x _* HEX_DIGIT ( HEX_DIGIT | _ )*

BIN_DIGIT → [0-1]

OCT_DIGIT → [0-7]

DEC_DIGIT → [0-9]

HEX_DIGIT → [0-9 a-f A-F]

[lex.token.literal.int.kind]

An integer literal has one of four forms:

[lex.token.literal.int.kind-dec]

- A decimal literal starts with a decimal digit and continues with any mixture of decimal digits and underscores.

[lex.token.literal.int.kind-hex]

- A hex literal starts with the character sequence `U+0030` `U+0078` (`0x`) and continues as any mixture (with at least one digit) of hex digits and underscores.

[lex.token.literal.int.kind-oct]

- An octal literal starts with the character sequence `U+0030` `U+006F` (`0o`) and continues as any mixture (with at least one digit) of octal digits and underscores.

[lex.token.literal.int.kind-bin]

- A binary literal starts with the character sequence `U+0030` `U+0062` (`0b`) and continues as any mixture (with at least one digit) of binary digits and underscores.

[lex.token.literal.int.restriction]

Like any literal, an integer literal may be followed (immediately, without any spaces) by a suffix as described above. The suffix may not begin with `e` or `E`, as that would be interpreted as the exponent of a floating-point literal. See Integer literal expressions for the effect of these suffixes.

Examples of integer literals which are accepted as literal expressions:

    #![allow(unused)]
    fn main() {
    #![allow(overflowing_literals)]
    123;
    123i32;
    123u32;
    123_u32;

    0xff;
    0xff_u8;
    0x01_f32; // integer 7986, not floating-point 1.0
    0x01_e3;  // integer 483, not floating-point 1000.0

    0o70;
    0o70_i16;

    0b1111_1111_1001_0000;
    0b1111_1111_1001_0000i64;
    0b________1;

    0usize;

    // These are too big for their type, but are accepted as literal expressions.
    128_i8;
    256_u8;

    // This is an integer literal, accepted as a floating-point literal expression.
    5f32;
    }

Note that `-1i8`, for example, is analyzed as two tokens: `-` followed by `1i8`.

Examples of integer literals which are not accepted as literal expressions:

    #![allow(unused)]
    fn main() {
    #[cfg(false)] {
    0invalidSuffix;
    123AFB43;
    0b010a;
    0xAB_CD_EF_GH;
    0b1111_f32;
    }
    }

[lex.token.literal.int.tuple-field]

#### Tuple index

[lex.token.literal.int.tuple-field.syntax]

Lexer
TUPLE_INDEX → DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL

[lex.token.literal.int.tuple-field.intro]

A tuple index is used to refer to the fields of tuples, tuple structs, and tuple enum variants.

[lex.token.literal.int.tuple-field.eq]

Tuple indices are compared with the literal token directly. Tuple indices start with `0` and each successive index increments the value by `1` as a decimal value. Thus, only decimal values will match, and the value must not have any extra `0` prefix characters.

Tuple indices may not include any suffixes (such as `usize`).

    #![allow(unused)]
    fn main() {
    let example = ("dog", "cat", "horse");
    let dog = example.0;
    let cat = example.1;
    // The following examples are invalid.
    let cat = example.01;  // ERROR no field named `01`
    let horse = example.0b10;  // ERROR no field named `0b10`
    let unicorn = example.0usize; // ERROR suffixes on a tuple index are invalid
    let underscore = example.0_0; // ERROR no field `0_0` on type `(&str, &str, &str)`
    }

[lex.token.literal.float]

#### Floating-point literals

[lex.token.literal.float.syntax]

Lexer
FLOAT_LITERAL →
DEC_LITERAL ( . DEC_LITERAL )? FLOAT_EXPONENT SUFFIX?
| DEC_LITERAL . DEC_LITERAL SUFFIX_NO_E?
| DEC_LITERAL .not immediately followed by `.`, `_` or an XID_Start character

FLOAT_EXPONENT →
( e | E ) ( + | - )? _* DEC_DIGIT ( DEC_DIGIT | _ )*

[lex.token.literal.float.form]

A floating-point literal has one of two forms:

- A decimal literal followed by a period character `U+002E` (`.`). This is optionally followed by another decimal literal, with an optional exponent.
- A single decimal literal followed by an exponent.

[lex.token.literal.float.suffix]

Like integer literals, a floating-point literal may be followed by a suffix, so long as the pre-suffix part does not end with `U+002E` (`.`). The suffix may not begin with `e` or `E` if the literal does not include an exponent. See Floating-point literal expressions for the effect of these suffixes.

Examples of floating-point literals which are accepted as literal expressions:

    #![allow(unused)]
    fn main() {
    123.0f64;
    0.1f64;
    0.1f32;
    12E+99_f64;
    let x: f64 = 2.;
    }

This last example is different because it is not possible to use the suffix syntax with a floating point literal ending in a period. `2.f64` would attempt to call a method named `f64` on `2`.

Note that `-1.0`, for example, is analyzed as two tokens: `-` followed by `1.0`.

Examples of floating-point literals which are not accepted as literal expressions:

    #![allow(unused)]
    fn main() {
    #[cfg(false)] {
    2.0f80;
    2e5f80;
    2e5e6;
    2.0e5e6;
    1.3e10u64;
    }
    }

[lex.token.literal.reserved]

#### Reserved forms similar to number literals

[lex.token.literal.reserved.syntax]

Lexer
RESERVED_NUMBER →
BIN_LITERAL [2-9]
| OCT_LITERAL [8-9]
| ( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) .not immediately followed by `.`, `_` or an XID_Start character
| ( BIN_LITERAL | OCT_LITERAL ) ( e | E )
| 0b _* <end of input or not BIN_DIGIT>
| 0o _* <end of input or not OCT_DIGIT>
| 0x _* <end of input or not HEX_DIGIT>
| DEC_LITERAL ( . DEC_LITERAL )? ( e | E ) ( + | - )? <end of input or not DEC_DIGIT>

[lex.token.literal.reserved.intro]

The following lexical forms similar to number literals are reserved forms. Due to the possible ambiguity these raise, they are rejected by the tokenizer instead of being interpreted as separate tokens.

[lex.token.literal.reserved.out-of-range]

- An unsuffixed binary or octal literal followed, without intervening whitespace, by a decimal digit out of the range for its radix.

[lex.token.literal.reserved.period]

- An unsuffixed binary, octal, or hexadecimal literal followed, without intervening whitespace, by a period character (with the same restrictions on what follows the period as for floating-point literals).

[lex.token.literal.reserved.exp]

- An unsuffixed binary or octal literal followed, without intervening whitespace, by the character `e` or `E`.

[lex.token.literal.reserved.empty-with-radix]

- Input which begins with one of the radix prefixes but is not a valid binary, octal, or hexadecimal literal (because it contains no digits).

[lex.token.literal.reserved.empty-exp]

- Input which has the form of a floating-point literal with no digits in the exponent.

Examples of reserved forms:

    #![allow(unused)]
    fn main() {
    0b0102;  // this is not `0b010` followed by `2`
    0o1279;  // this is not `0o127` followed by `9`
    0x80.0;  // this is not `0x80` followed by `.` and `0`
    0b101e;  // this is not a suffixed literal, or `0b101` followed by `e`
    0b;      // this is not an integer literal, or `0` followed by `b`
    0b_;     // this is not an integer literal, or `0` followed by `b_`
    2e;      // this is not a floating-point literal, or `2` followed by `e`
    2.0e;    // this is not a floating-point literal, or `2.0` followed by `e`
    2em;     // this is not a suffixed literal, or `2` followed by `em`
    2.0em;   // this is not a suffixed literal, or `2.0` followed by `em`
    }

[lex.token.life]

## Lifetimes and loop labels

[lex.token.life.syntax]

Lexer
LIFETIME_TOKEN →
RAW_LIFETIME
| ' IDENTIFIER_OR_KEYWORDnot immediately followed by `'`

LIFETIME_OR_LABEL →
RAW_LIFETIME
| ' NON_KEYWORD_IDENTIFIERnot immediately followed by `'`

RAW_LIFETIME →
'r# IDENTIFIER_OR_KEYWORDnot immediately followed by `'`

RESERVED_RAW_LIFETIME → 'r# ( _ | crate | self | Self | super )not immediately followed by `'`

[lex.token.life.intro]

Lifetime parameters and loop labels use LIFETIME_OR_LABEL tokens. Any LIFETIME_TOKEN will be accepted by the lexer, and for example, can be used in macros.

[lex.token.life.raw.intro]

A raw lifetime is like a normal lifetime, but its identifier is prefixed by `r#`. (Note that the `r#` prefix is not included as part of the actual lifetime.)

[lex.token.life.raw.allowed]

Unlike a normal lifetime, a raw lifetime may be any strict or reserved keyword except the ones listed above for `RAW_LIFETIME`.

[lex.token.life.raw.reserved]

It is an error to use the RESERVED_RAW_LIFETIME token.

[lex.token.life.raw.edition2021]

> 2021 Edition differences

> Raw lifetimes are accepted in the 2021 edition or later. In earlier editions the token `'r#lt` is lexed as `'r # lt`.

[lex.token.punct]

## Punctuation

[lex.token.punct.intro]

Punctuation tokens are used as operators, separators, and other parts of the grammar.

[lex.token.punct.syntax]

Lexer
PUNCTUATION →
...
| ..=
| <<=
| >>=
| !=
| %=
| &&
| &=
| *=
| +=
| -=
| ->
| ..
| /=
| ::
| <-
| <<
| <=
| ==
| =>
| >=
| >>
| >
| ^=
| |=
| ||
| !
| #
| $
| %
| &
| (
| )
| *
| +
| ,
| -
| .
| /
| :
| ;
| <
| =
| ?
| @
| [
| ]
| ^
| {
| |
| }
| ~

> Note

> See the syntax index for links to how punctuation characters are used.

[lex.token.delim]

## Delimiters

Bracket punctuation is used in various parts of the grammar. An open bracket must always be paired with a close bracket. Brackets and the tokens within them are referred to as “token trees” in macros. The three types of brackets are:

Bracket | Type
--- | ---
`{` `}` | Curly braces
`[` `]` | Square brackets
`(` `)` | Parentheses

[lex.token.reserved]

## Reserved tokens

[lex.token.reserved.intro]

Several token forms are reserved for future use or to avoid confusion. It is an error for the source input to match one of these forms.

[lex.token.reserved.syntax]

Lexer
RESERVED_TOKEN →
RESERVED_GUARDED_STRING_LITERAL
| RESERVED_NUMBER
| RESERVED_POUNDS
| RESERVED_RAW_IDENTIFIER
| RESERVED_RAW_LIFETIME
| RESERVED_TOKEN_DOUBLE_QUOTE
| RESERVED_TOKEN_LIFETIME
| RESERVED_TOKEN_POUND
| RESERVED_TOKEN_SINGLE_QUOTE

[lex.token.reserved-prefix]

## Reserved prefixes

[lex.token.reserved-prefix.syntax]

Lexer
RESERVED_TOKEN_DOUBLE_QUOTE →
IDENTIFIER_OR_KEYWORDexcept `b` or `c` or `r` or `br` or `cr` "

RESERVED_TOKEN_SINGLE_QUOTE →
IDENTIFIER_OR_KEYWORDexcept `b` '

RESERVED_TOKEN_POUND →
IDENTIFIER_OR_KEYWORDexcept `r` or `br` or `cr` #

RESERVED_TOKEN_LIFETIME →
' IDENTIFIER_OR_KEYWORDexcept `r` #

[lex.token.reserved-prefix.intro]

Some lexical forms known as reserved prefixes are reserved for future use.

[lex.token.reserved-prefix.id]

Source input which would otherwise be lexically interpreted as a non-raw identifier (or a keyword) which is immediately followed by a `#`, `'`, or `"` character (without intervening whitespace) is identified as a reserved prefix.

[lex.token.reserved-prefix.raw-token]

Note that raw identifiers, raw string literals, and raw byte string literals may contain a `#` character but are not interpreted as containing a reserved prefix.

[lex.token.reserved-prefix.strings]

Similarly the `r`, `b`, `br`, `c`, and `cr` prefixes used in raw string literals, byte literals, byte string literals, raw byte string literals, C string literals, and raw C string literals are not interpreted as reserved prefixes.

[lex.token.reserved-prefix.life]

Source input which would otherwise be lexically interpreted as a non-raw lifetime (or a keyword) which is immediately followed by a `#` character (without intervening whitespace) is identified as a reserved lifetime prefix.

[lex.token.reserved-prefix.edition2021]

> 2021 Edition differences

> Starting with the 2021 edition, reserved prefixes are reported as an error by the lexer (in particular, they cannot be passed to macros).

> Before the 2021 edition, reserved prefixes are accepted by the lexer and interpreted as multiple tokens (for example, one token for the identifier or keyword, followed by a `#` token).

> Examples accepted in all editions:

>     #![allow(unused)]
>     fn main() {
>     macro_rules! lexes {($($_:tt)*) => {}}
>     lexes!{a #foo}
>     lexes!{continue 'foo}
>     lexes!{match "..." {}}
>     lexes!{r#let#foo}         // three tokens: r#let # foo
>     lexes!{'prefix #lt}
>     }

> Examples accepted before the 2021 edition but rejected later:

>     #![allow(unused)]
>     fn main() {
>     macro_rules! lexes {($($_:tt)*) => {}}
>     lexes!{a#foo}
>     lexes!{continue'foo}
>     lexes!{match"..." {}}
>     lexes!{'prefix#lt}
>     }

[lex.token.reserved-guards]

## Reserved guards

[lex.token.reserved-guards.syntax]

Lexer
RESERVED_GUARDED_STRING_LITERAL → #+ STRING_LITERAL

RESERVED_POUNDS → #2..

[lex.token.reserved-guards.intro]

The reserved guards are syntax reserved for future use, and will generate a compile error if used.

[lex.token.reserved-guards.string-literal]

The reserved guarded string literal is a token of one or more `U+0023` (`#`) immediately followed by a STRING_LITERAL.

[lex.token.reserved-guards.pounds]

The reserved pounds is a token of two or more `U+0023` (`#`).

[lex.token.reserved-guards.edition2024]

> 2024 Edition differences

> Before the 2024 edition, reserved guards are accepted by the lexer and interpreted as multiple tokens. For example, the `#"foo"#` form is interpreted as three tokens. `##` is interpreted as two tokens.

1. The number of `#`s on each side of the same literal must be equivalent. ↩

2. All number literals allow `_` as a visual separator: `1_234.0E+18f64` ↩

3. See lex.token.literal.char-escape.unicode. ↩

[macro]

# Macros

[macro.intro]

The functionality and syntax of Rust can be extended with custom definitions called macros. They are given names, and invoked through a consistent syntax: `some_extension!(...)`.

There are two ways to define new macros:

- Macros by Example define new syntax in a higher-level, declarative way.
- Procedural Macros define function-like macros, custom derives, and custom attributes using functions that operate on input tokens.

[macro.invocation]

## Macro invocation

[macro.invocation.syntax]

Syntax
MacroInvocation →
SimplePath ! DelimTokenTree

DelimTokenTree →
( TokenTree* )
| [ TokenTree* ]
| { TokenTree* }

TokenTree →
Tokenexcept delimiters | DelimTokenTree

MacroInvocationSemi →
SimplePath ! ( TokenTree* ) ;
| SimplePath ! [ TokenTree* ] ;
| SimplePath ! { TokenTree* }

[macro.invocation.intro]

A macro invocation expands a macro at compile time and replaces the invocation with the result of the macro. Macros may be invoked in the following situations:

[macro.invocation.expr]

- Expressions and statements

[macro.invocation.pattern]

- Patterns

[macro.invocation.type]

- Types

[macro.invocation.item]

- Items including associated items

[macro.invocation.nested]

- `macro_rules` transcribers

[macro.invocation.extern]

- External blocks

[macro.invocation.item-statement]

When used as an item or a statement, the MacroInvocationSemi form is used where a semicolon is required at the end when not using curly braces. Visibility qualifiers are never allowed before a macro invocation or `macro_rules` definition.

    #![allow(unused)]
    fn main() {
    // Used as an expression.
    let x = vec![1,2,3];

    // Used as a statement.
    println!("Hello!");

    // Used in a pattern.
    macro_rules! pat {
        ($i:ident) => (Some($i))
    }

    if let pat!(x) = Some(1) {
        assert_eq!(x, 1);
    }

    // Used in a type.
    macro_rules! Tuple {
        { $A:ty, $B:ty } => { ($A, $B) };
    }

    type N2 = Tuple!(i32, i32);

    // Used as an item.
    use std::cell::RefCell;
    thread_local!(static FOO: RefCell<u32> = RefCell::new(1));

    // Used as an associated item.
    macro_rules! const_maker {
        ($t:ty, $v:tt) => { const CONST: $t = $v; };
    }
    trait T {
        const_maker!{i32, 7}
    }

    // Macro calls within macros.
    macro_rules! example {
        () => { println!("Macro call in a macro!") };
    }
    // Outer macro `example` is expanded, then inner macro `println` is expanded.
    example!();
    }

[macro.invocation.name-resolution]

Macros invocations can be resolved via two kinds of scopes:

- Textual Scope
  - Textual scope `macro_rules`
- Path-based scope
  - Path-based scope `macro_rules`
  - Procedural macros

[macro.decl]

# Macros by example

[macro.decl.syntax]

Syntax
MacroRulesDefinition →
macro_rules ! IDENTIFIER MacroRulesDef

MacroRulesDef →
( MacroRules ) ;
| [ MacroRules ] ;
| { MacroRules }

MacroRules →
MacroRule ( ; MacroRule )* ;?

MacroRule →
MacroMatcher => MacroTranscriber

MacroMatcher →
( MacroMatch* )
| [ MacroMatch* ]
| { MacroMatch* }

MacroMatch →
Tokenexcept `$` and delimiters
| MacroMatcher
| $ ( IDENTIFIER_OR_KEYWORDexcept `crate` | RAW_IDENTIFIER ) : MacroFragSpec
| $ ( MacroMatch+ ) MacroRepSep? MacroRepOp

MacroFragSpec →
block | expr | expr_2021 | ident | item | lifetime | literal
| meta | pat | pat_param | path | stmt | tt | ty | vis

MacroRepSep → Tokenexcept delimiters and MacroRepOp

MacroRepOp → * | + | ?

MacroTranscriber → DelimTokenTree

[macro.decl.intro]

`macro_rules` allows users to define syntax extension in a declarative way. We call such extensions “macros by example” or simply “macros”.

Each macro by example has a name, and one or more rules. Each rule has two parts: a matcher, describing the syntax that it matches, and a transcriber, describing the syntax that will replace a successfully matched invocation. Both the matcher and the transcriber must be surrounded by delimiters. Macros can expand to expressions, statements, items (including traits, impls, and foreign items), types, or patterns.

[macro.decl.transcription]

## Transcribing

[macro.decl.transcription.intro]

When a macro is invoked, the macro expander looks up macro invocations by name, and tries each macro rule in turn. It transcribes the first successful match; if this results in an error, then future matches are not tried.

[macro.decl.transcription.lookahead]

When matching, no lookahead is performed; if the compiler cannot unambiguously determine how to parse the macro invocation one token at a time, then it is an error. In the following example, the compiler does not look ahead past the identifier to see if the following token is a `)`, even though that would allow it to parse the invocation unambiguously:

    #![allow(unused)]
    fn main() {
    macro_rules! ambiguity {
        ($($i:ident)* $j:ident) => { };
    }

    ambiguity!(error); // Error: local ambiguity
    }

[macro.decl.transcription.syntax]

In both the matcher and the transcriber, the `$` token is used to invoke special behaviours from the macro engine (described below in Metavariables and Repetitions). Tokens that aren’t part of such an invocation are matched and transcribed literally, with one exception. The exception is that the outer delimiters for the matcher will match any pair of delimiters. Thus, for instance, the matcher `(())` will match `{()}` but not `{{}}`. The character `$` cannot be matched or transcribed literally.

[macro.decl.transcription.fragment]

### Forwarding a matched fragment

When forwarding a matched fragment to another macro-by-example, matchers in the second macro will see an opaque AST of the fragment type. The second macro can’t use literal tokens to match the fragments in the matcher, only a fragment specifier of the same type. The `ident`, `lifetime`, and `tt` fragment types are an exception, and can be matched by literal tokens. The following illustrates this restriction:

    #![allow(unused)]
    fn main() {
    macro_rules! foo {
        ($l:expr) => { bar!($l); }
    // ERROR:               ^^ no rules expected this token in macro call
    }

    macro_rules! bar {
        (3) => {}
    }

    foo!(3);
    }

The following illustrates how tokens can be directly matched after matching a `tt` fragment:

    #![allow(unused)]
    fn main() {
    // compiles OK
    macro_rules! foo {
        ($l:tt) => { bar!($l); }
    }

    macro_rules! bar {
        (3) => {}
    }

    foo!(3);
    }

[macro.decl.meta]

## Metavariables

[macro.decl.meta.intro]

In the matcher, `$` name `:` fragment-specifier matches a Rust syntax fragment of the kind specified and binds it to the metavariable `$`name.

[macro.decl.meta.specifier]

Valid fragment specifiers are:

- `block`: a BlockExpression
- `expr`: an Expression
- `expr_2021`: an Expression except UnderscoreExpression and ConstBlockExpression (see macro.decl.meta.edition2024)
- `ident`: an IDENTIFIER_OR_KEYWORD except `_`, RAW_IDENTIFIER, or `$crate`
- `item`: an Item
- `lifetime`: a LIFETIME_TOKEN
- `literal`: matches `-`?LiteralExpression
- `meta`: an Attr, the contents of an attribute
- `pat`: a Pattern (see macro.decl.meta.edition2021)
- `pat_param`: a PatternNoTopAlt
- `path`: a TypePath style path
- `stmt`: a Statement without the trailing semicolon (except for item statements that require semicolons)
- `tt`: a TokenTree (a single token or tokens in matching delimiters `()`, `[]`, or `{}`)
- `ty`: a Type
- `vis`: a possibly empty Visibility qualifier

[macro.decl.meta.transcription]

In the transcriber, metavariables are referred to simply by `$`name, since the fragment kind is specified in the matcher. Metavariables are replaced with the syntax element that matched them. Metavariables can be transcribed more than once or not at all.

[macro.decl.meta.dollar-crate]

The keyword metavariable `$crate` can be used to refer to the current crate.

[macro.decl.meta.edition2021]

> 2021 Edition differences

> Starting with the 2021 edition, `pat` fragment-specifiers match top-level or-patterns (that is, they accept Pattern).

> Before the 2021 edition, they match exactly the same fragments as `pat_param` (that is, they accept PatternNoTopAlt).

> The relevant edition is the one in effect for the `macro_rules!` definition.

[macro.decl.meta.edition2024]

> 2024 Edition differences

> Before the 2024 edition, `expr` fragment specifiers do not match UnderscoreExpression or ConstBlockExpression at the top level. They are allowed within subexpressions.

> The `expr_2021` fragment specifier exists to maintain backwards compatibility with editions before 2024.

[macro.decl.repetition]

## Repetitions

[macro.decl.repetition.intro]

In both the matcher and transcriber, repetitions are indicated by placing the tokens to be repeated inside `$(`…`)`, followed by a repetition operator, optionally with a separator token between.

[macro.decl.repetition.separator]

The separator token can be any token other than a delimiter or one of the repetition operators, but `;` and `,` are the most common. For instance, `$( $i:ident ),*` represents any number of identifiers separated by commas. Nested repetitions are permitted.

[macro.decl.repetition.operators]

The repetition operators are:

- `*` — indicates any number of repetitions.
- `+` — indicates any number but at least one.
- `?` — indicates an optional fragment with zero or one occurrence.

[macro.decl.repetition.optional-restriction]

Since `?` represents at most one occurrence, it cannot be used with a separator.

[macro.decl.repetition.fragment]

The repeated fragment both matches and transcribes to the specified number of the fragment, separated by the separator token. Metavariables are matched to every repetition of their corresponding fragment. For instance, the `$( $i:ident ),*` example above matches `$i` to all of the identifiers in the list.

During transcription, additional restrictions apply to repetitions so that the compiler knows how to expand them properly:

1. A metavariable must appear in exactly the same number, kind, and nesting order of repetitions in the transcriber as it did in the matcher. So for the matcher `$( $i:ident ),*`, the transcribers `=> { $i }`, `=> { $( $( $i )* )* }`, and `=> { $( $i )+ }` are all illegal, but `=> { $( $i );* }` is correct and replaces a comma-separated list of identifiers with a semicolon-separated list.
2. Each repetition in the transcriber must contain at least one metavariable to decide how many times to expand it. If multiple metavariables appear in the same repetition, they must be bound to the same number of fragments. For instance, `( $( $i:ident ),* ; $( $j:ident ),* ) => (( $( ($i,$j) ),* ))` must bind the same number of `$i` fragments as `$j` fragments. This means that invoking the macro with `(a, b, c; d, e, f)` is legal and expands to `((a,d), (b,e), (c,f))`, but `(a, b, c; d, e)` is illegal because it does not have the same number. This requirement applies to every layer of nested repetitions.

[macro.decl.scope]

## Scoping, exporting, and importing

[macro.decl.scope.intro]

For historical reasons, the scoping of macros by example does not work entirely like items. Macros have two forms of scope: textual scope, and path-based scope. Textual scope is based on the order that things appear in source files, or even across multiple files, and is the default scoping. It is explained further below. Path-based scope works exactly the same way that item scoping does. The scoping, exporting, and importing of macros is controlled largely by attributes.

[macro.decl.scope.unqualified]

When a macro is invoked by an unqualified identifier (not part of a multi-part path), it is first looked up in textual scoping. If this does not yield any results, then it is looked up in path-based scoping. If the macro’s name is qualified with a path, then it is only looked up in path-based scoping.

    use lazy_static::lazy_static; // Path-based import.

    macro_rules! lazy_static { // Textual definition.
        (lazy) => {};
    }

    lazy_static!{lazy} // Textual lookup finds our macro first.
    self::lazy_static!{} // Path-based lookup ignores our macro, finds imported one.

[macro.decl.scope.textual]

### Textual scope

[macro.decl.scope.textual.intro]

Textual scope is based largely on the order that things appear in source files, and works similarly to the scope of local variables declared with `let` except it also applies at the module level. When `macro_rules!` is used to define a macro, the macro enters the scope after the definition (note that it can still be used recursively, since names are looked up from the invocation site), up until its surrounding scope, typically a module, is closed. This can enter child modules and even span across multiple files:

    //// src/lib.rs
    mod has_macro {
        // m!{} // Error: m is not in scope.

        macro_rules! m {
            () => {};
        }
        m!{} // OK: appears after declaration of m.

        mod uses_macro;
    }

    // m!{} // Error: m is not in scope.

    //// src/has_macro/uses_macro.rs

    m!{} // OK: appears after declaration of m in src/lib.rs

[macro.decl.scope.textual.shadow]

It is not an error to define a macro multiple times; the most recent declaration will shadow the previous one unless it has gone out of scope.

    #![allow(unused)]
    fn main() {
    macro_rules! m {
        (1) => {};
    }

    m!(1);

    mod inner {
        m!(1);

        macro_rules! m {
            (2) => {};
        }
        // m!(1); // Error: no rule matches '1'
        m!(2);

        macro_rules! m {
            (3) => {};
        }
        m!(3);
    }

    m!(1);
    }

Macros can be declared and used locally inside functions as well, and work similarly:

    #![allow(unused)]
    fn main() {
    fn foo() {
        // m!(); // Error: m is not in scope.
        macro_rules! m {
            () => {};
        }
        m!();
    }

    // m!(); // Error: m is not in scope.
    }

[macro.decl.scope.textual.shadow.path-based]

Textual scope name bindings for macros shadow path-based scope bindings to macros.

    #![allow(unused)]
    fn main() {
    macro_rules! m2 {
        () => {
            println!("m2");
        };
    }

    // Resolves to path-based candidate from use declaration below.
    m!(); // prints "m2\n"

    // Introduce second candidate for `m` with textual scope.
    //
    // This shadows path-based candidate from below for the rest of this
    // example.
    macro_rules! m {
        () => {
            println!("m");
        };
    }

    // Introduce `m2` macro as path-based candidate.
    //
    // This item is in scope for this entire example, not just below the
    // use declaration.
    use m2 as m;

    // Resolves to the textual macro candidate from above the use
    // declaration.
    m!(); // prints "m\n"
    }

> Note

> For areas where shadowing is not allowed, see name resolution ambiguities.

[macro.decl.scope.path-based]

### Path-based scope

[macro.decl.scope.path-based.intro]

By default, a macro has no path-based scope. Macros can gain path-based scope in two ways:

- Use declaration re-export
- `macro_export`

[macro.decl.scope.path.reexport]

Macros can be re-exported to give them path-based scope from a module other than the crate root.

    #![allow(unused)]
    fn main() {
    mac::m!(); // OK: Path-based lookup finds `m` in the mac module.

    mod mac {
        // Introduce macro `m` with textual scope.
        macro_rules! m {
            () => {};
        }

        // Reexport with path-based scope from within `m`'s textual scope.
        pub(crate) use m;
    }
    }

[macro.decl.scope.path-based.visibility]

Macros have an implicit visibility of `pub(crate)`. `#[macro_export]` changes the implicit visibility to `pub`.

    #![allow(unused)]
    fn main() {
    // Implicit visibility is `pub(crate)`.
    macro_rules! private_m {
        () => {};
    }

    // Implicit visibility is `pub`.
    #[macro_export]
    macro_rules! pub_m {
        () => {};
    }

    pub(crate) use private_m as private_macro; // OK.
    pub use pub_m as pub_macro; // OK.
    }

    #![allow(unused)]
    fn main() {
    // Implicit visibility is `pub(crate)`.
    macro_rules! private_m {
        () => {};
    }

    // Implicit visibility is `pub`.
    #[macro_export]
    macro_rules! pub_m {
        () => {};
    }

    pub(crate) use private_m as private_macro; // OK.
    pub use pub_m as pub_macro; // OK.

    pub use private_m; // ERROR: `private_m` is only public within
                       // the crate and cannot be re-exported outside.
    }

[macro.decl.scope.macro_use]

### The `macro_use` attribute

[macro.decl.scope.macro_use.intro]

The `macro_use` attribute has two purposes: it may be used on modules to extend the scope of macros defined within them, and it may be used on `extern crate` to import macros from another crate into the `macro_use` prelude.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[macro_use]
>     mod inner {
>         macro_rules! m {
>             () => {};
>         }
>     }
>     m!();
>     }

>     #[macro_use]
>     extern crate log;

[macro.decl.scope.macro_use.syntax]

When used on modules, the `macro_use` attribute uses the MetaWord syntax.

When used on `extern crate`, it uses the MetaWord and MetaListIdents syntaxes. For more on how these syntaxes may be used, see macro.decl.scope.macro_use.prelude.

[macro.decl.scope.macro_use.allowed-positions]

The `macro_use` attribute may be applied to modules or `extern crate`.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[macro.decl.scope.macro_use.extern-crate-self]

The `macro_use` attribute may not be used on `extern crate self`.

[macro.decl.scope.macro_use.duplicates]

The `macro_use` attribute may be used any number of times on a form.

Multiple instances of `macro_use` in the MetaListIdents syntax may be specified. The union of all specified macros will be imported.

> Note

> On modules, `rustc` lints against any MetaWord `macro_use` attributes following the first.

> On `extern crate`, `rustc` lints against any `macro_use` attributes that have no effect due to not importing any macros not already imported by another `macro_use` attribute. If two or more MetaListIdents `macro_use` attributes import the same macro, the first is linted against. If any MetaWord `macro_use` attributes are present, all MetaListIdents `macro_use` attributes are linted against. If two or more MetaWord `macro_use` attributes are present, the ones following the first are linted against.

[macro.decl.scope.macro_use.mod-decl]

When `macro_use` is used on a module, the module’s macro scope extends beyond the module’s lexical scope.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[macro_use]
>     mod inner {
>         macro_rules! m {
>             () => {};
>         }
>     }
>     m!(); // OK
>     }

[macro.decl.scope.macro_use.prelude]

Specifying `macro_use` on an `extern crate` declaration in the crate root imports exported macros from that crate.

Macros imported this way are imported into the `macro_use` prelude, not textually, which means that they can be shadowed by any other name. Macros imported by `macro_use` can be used before the import statement.

> Note

> `rustc` currently prefers the last macro imported in case of conflict. Don’t rely on this. This behavior is unusual, as imports in Rust are generally order-independent. This behavior of `macro_use` may change in the future.

> For details, see Rust issue #148025.

When using the MetaWord syntax, all exported macros are imported. When using the MetaListIdents syntax, only the specified macros are imported.

> Example

>     #[macro_use(lazy_static)] // Or `#[macro_use]` to import all macros.
>     extern crate lazy_static;

>     lazy_static!{}
>     // self::lazy_static!{} // ERROR: lazy_static is not defined in `self`.

[macro.decl.scope.macro_use.export]

Macros to be imported with `macro_use` must be exported with `macro_export`.

[macro.decl.scope.macro_export]

### The `macro_export` attribute

[macro.decl.scope.macro_export.intro]

The `macro_export` attribute exports the macro from the crate and makes it available in the root of the crate for path-based resolution.

> Example

>     #![allow(unused)]
>     fn main() {
>     self::m!();
>     //  ^^^^ OK: Path-based lookup finds `m` in the current module.
>     m!(); // As above.

>     mod inner {
>         super::m!();
>         crate::m!();
>     }

>     mod mac {
>         #[macro_export]
>         macro_rules! m {
>             () => {};
>         }
>     }
>     }

[macro.decl.scope.macro_export.syntax]

The `macro_export` attribute uses the MetaWord and MetaListIdents syntaxes. With the MetaListIdents syntax, it accepts a single `local_inner_macros` value.

[macro.decl.scope.macro_export.allowed-positions]

The `macro_export` attribute may be applied to `macro_rules` definitions.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[macro.decl.scope.macro_export.duplicates]

Only the first use of `macro_export` on a macro has effect.

> Note

> `rustc` lints against any use following the first.

[macro.decl.scope.macro_export.path-based]

By default, macros only have textual scope and cannot be resolved by path. When the `macro_export` attribute is used, the macro is made available in the crate root and can be referred to by its path.

> Example

> Without `macro_export`, macros only have textual scope, so path-based resolution of the macro fails.

>     macro_rules! m {
>         () => {};
>     }
>     self::m!(); // ERROR
>     crate::m!(); // ERROR
>     fn main() {}

> With `macro_export`, path-based resolution works.

>     #[macro_export]
>     macro_rules! m {
>         () => {};
>     }
>     self::m!(); // OK
>     crate::m!(); // OK
>     fn main() {}

[macro.decl.scope.macro_export.export]

The `macro_export` attribute causes a macro to be exported from the crate root so that it can be referred to in other crates by path.

> Example

> Given the following in a `log` crate:

>     #![allow(unused)]
>     fn main() {
>     #[macro_export]
>     macro_rules! warn {
>         ($message:expr) => { eprintln!("WARN: {}", $message) };
>     }
>     }

> From another crate, you can refer to the macro by path:

>     fn main() {
>         log::warn!("example warning");
>     }

[macro.decl.scope.macro_export.macro_use]

`macro_export` allows the use of `macro_use` on an `extern crate` to import the macro into the `macro_use` prelude.

> Example

> Given the following in a `log` crate:

>     #![allow(unused)]
>     fn main() {
>     #[macro_export]
>     macro_rules! warn {
>         ($message:expr) => { eprintln!("WARN: {}", $message) };
>     }
>     }

> Using `macro_use` in a dependent crate allows you to use the macro from the prelude:

>     #[macro_use]
>     extern crate log;

>     pub mod util {
>         pub fn do_thing() {
>             // Resolved via macro prelude.
>             warn!("example warning");
>         }
>     }

[macro.decl.scope.macro_export.local_inner_macros]

Adding `local_inner_macros` to the `macro_export` attribute causes all single-segment macro invocations in the macro definition to have an implicit `$crate::` prefix.

> Note

> This is intended primarily as a tool to migrate code written before `$crate` was added to the language to work with Rust 2018’s path-based imports of macros. Its use is discouraged in new code.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[macro_export(local_inner_macros)]
>     macro_rules! helped {
>         () => { helper!() } // Automatically converted to $crate::helper!().
>     }

>     #[macro_export]
>     macro_rules! helper {
>         () => { () }
>     }
>     }

[macro.decl.hygiene]

## Hygiene

[macro.decl.hygiene.intro]

Macros by example have mixed-site hygiene. This means that loop labels, block labels, and local variables are looked up at the macro definition site while other symbols are looked up at the macro invocation site. For example:

    #![allow(unused)]
    fn main() {
    let x = 1;
    fn func() {
        unreachable!("this is never called")
    }

    macro_rules! check {
        () => {
            assert_eq!(x, 1); // Uses `x` from the definition site.
            func();           // Uses `func` from the invocation site.
        };
    }

    {
        let x = 2;
        fn func() { /* does not panic */ }
        check!();
    }
    }

Labels and local variables defined in macro expansion are not shared between invocations, so this code doesn’t compile:

    #![allow(unused)]
    fn main() {
    macro_rules! m {
        (define) => {
            let x = 1;
        };
        (refer) => {
            dbg!(x);
        };
    }

    m!(define);
    m!(refer);
    }

[macro.decl.hygiene.crate]

A special case is the `$crate` metavariable. It refers to the crate defining the macro, and can be used at the start of the path to look up items or macros which are not in scope at the invocation site.

    //// Definitions in the `helper_macro` crate.
    #[macro_export]
    macro_rules! helped {
        // () => { helper!() } // This might lead to an error due to 'helper' not being in scope.
        () => { $crate::helper!() }
    }

    #[macro_export]
    macro_rules! helper {
        () => { () }
    }

    //// Usage in another crate.
    // Note that `helper_macro::helper` is not imported!
    use helper_macro::helped;

    fn unit() {
        helped!();
    }

Note that, because `$crate` refers to the current crate, it must be used with a fully qualified module path when referring to non-macro items:

    #![allow(unused)]
    fn main() {
    pub mod inner {
        #[macro_export]
        macro_rules! call_foo {
            () => { $crate::inner::foo() };
        }

        pub fn foo() {}
    }
    }

[macro.decl.hygiene.vis]

Additionally, even though `$crate` allows a macro to refer to items within its own crate when expanding, its use has no effect on visibility. An item or macro referred to must still be visible from the invocation site. In the following example, any attempt to invoke `call_foo!()` from outside its crate will fail because `foo()` is not public.

    #![allow(unused)]
    fn main() {
    #[macro_export]
    macro_rules! call_foo {
        () => { $crate::foo() };
    }

    fn foo() {}
    }

> Note

> Prior to Rust 1.30, `$crate` and `local_inner_macros` were unsupported. They were added alongside path-based imports of macros, to ensure that helper macros did not need to be manually imported by users of a macro-exporting crate. Crates written for earlier versions of Rust that use helper macros need to be modified to use `$crate` or `local_inner_macros` to work well with path-based imports.

[macro.decl.follow-set]

## Follow-set ambiguity restrictions

[macro.decl.follow-set.intro]

The parser used by the macro system is reasonably powerful, but it is limited in order to prevent ambiguity in current or future versions of the language.

[macro.decl.follow-set.token-restriction]

In particular, in addition to the rule about ambiguous expansions, a nonterminal matched by a metavariable must be followed by a token which has been decided can be safely used after that kind of match.

As an example, a macro matcher like `$i:expr [ , ]` could in theory be accepted in Rust today, since `[,]` cannot be part of a legal expression and therefore the parse would always be unambiguous. However, because `[` can start trailing expressions, `[` is not a character which can safely be ruled out as coming after an expression. If `[,]` were accepted in a later version of Rust, this matcher would become ambiguous or would misparse, breaking working code. Matchers like `$i:expr,` or `$i:expr;` would be legal, however, because `,` and `;` are legal expression separators. The specific rules are:

[macro.decl.follow-set.token-expr-stmt]

- `expr` and `stmt` may only be followed by one of: `=>`, `,`, or `;`.

[macro.decl.follow-set.token-pat_param]

- `pat_param` may only be followed by one of: `=>`, `,`, `=`, `|`, `if`, or `in`.

[macro.decl.follow-set.token-pat]

- `pat` may only be followed by one of: `=>`, `,`, `=`, `if`, or `in`.

[macro.decl.follow-set.token-path-ty]

- `path` and `ty` may only be followed by one of: `=>`, `,`, `=`, `|`, `;`, `:`, `>`, `>>`, `[`, `{`, `as`, `where`, or a macro variable of `block` fragment specifier.

[macro.decl.follow-set.token-vis]

- `vis` may only be followed by one of: `,`, an identifier other than a non-raw `priv`, any token that can begin a type, or a metavariable with a `ident`, `ty`, or `path` fragment specifier.

[macro.decl.follow-set.token-other]

- All other fragment specifiers have no restrictions.

[macro.decl.follow-set.edition2021]

> 2021 Edition differences

> Before the 2021 edition, `pat` may also be followed by `|`.

[macro.decl.follow-set.repetition]

When repetitions are involved, then the rules apply to every possible number of expansions, taking separators into account. This means:

- If the repetition includes a separator, that separator must be able to follow the contents of the repetition.
- If the repetition can repeat multiple times (`*` or `+`), then the contents must be able to follow themselves.
- The contents of the repetition must be able to follow whatever comes before, and whatever comes after must be able to follow the contents of the repetition.
- If the repetition can match zero times (`*` or `?`), then whatever comes after must be able to follow whatever comes before.

For more detail, see the formal specification.

[macro.proc]

# Procedural macros

[macro.proc.intro]

Procedural macros allow creating syntax extensions as execution of a function. Procedural macros come in one of three flavors:

- Function-like macros - `custom!(...)`
- Derive macros - `#[derive(CustomDerive)]`
- Attribute macros - `#[CustomAttribute]`

Procedural macros allow you to run code at compile time that operates over Rust syntax, both consuming and producing Rust syntax. You can sort of think of procedural macros as functions from an AST to another AST.

[macro.proc.def]

Procedural macros must be defined in the root of a crate with the crate type of `proc-macro`. The macros may not be used from the crate where they are defined, and can only be used when imported in another crate.

> Note

> When using Cargo, Procedural macro crates are defined with the `proc-macro` key in your manifest:

>     [lib]
>     proc-macro = true

[macro.proc.result]

As functions, they must either return syntax, panic, or loop endlessly. Returned syntax either replaces or adds the syntax depending on the kind of procedural macro. Panics are caught by the compiler and are turned into a compiler error. Endless loops are not caught by the compiler which hangs the compiler.

Procedural macros run during compilation, and thus have the same resources that the compiler has. For example, standard input, error, and output are the same that the compiler has access to. Similarly, file access is the same. Because of this, procedural macros have the same security concerns that Cargo’s build scripts have.

[macro.proc.error]

Procedural macros have two ways of reporting errors. The first is to panic. The second is to emit a `compile_error` macro invocation.

[macro.proc.proc_macro-crate]

## The `proc_macro` crate

[macro.proc.proc_macro-crate.intro]

Procedural macro crates almost always will link to the compiler-provided `proc_macro` crate. The `proc_macro` crate provides types required for writing procedural macros and facilities to make it easier.

[macro.proc.proc_macro-crate.token-stream]

This crate primarily contains a `TokenStream` type. Procedural macros operate over token streams instead of AST nodes, which is a far more stable interface over time for both the compiler and for procedural macros to target. A token stream is roughly equivalent to `Vec<TokenTree>` where a `TokenTree` can roughly be thought of as lexical token. For example `foo` is an `Ident` token, `.` is a `Punct` token, and `1.2` is a `Literal` token. The `TokenStream` type, unlike `Vec<TokenTree>`, is cheap to clone.

[macro.proc.proc_macro-crate.span]

All tokens have an associated `Span`. A `Span` is an opaque value that cannot be modified but can be manufactured. `Span`s represent an extent of source code within a program and are primarily used for error reporting. While you cannot modify a `Span` itself, you can always change the `Span` associated with any token, such as through getting a `Span` from another token.

[macro.proc.hygiene]

## Procedural macro hygiene

Procedural macros are unhygienic. This means they behave as if the output token stream was simply written inline to the code it’s next to. This means that it’s affected by external items and also affects external imports.

Macro authors need to be careful to ensure their macros work in as many contexts as possible given this limitation. This often includes using absolute paths to items in libraries (for example, `::std::option::Option` instead of `Option`) or by ensuring that generated functions have names that are unlikely to clash with other functions (like `__internal_foo` instead of `foo`).

[macro.proc.proc_macro]

## The `proc_macro` attribute

[macro.proc.proc_macro.intro]

The `proc_macro` attribute defines a function-like procedural macro.

> Example

> This macro definition ignores its input and emits a function `answer` into its scope.

>     #![crate_type = "proc-macro"]
>     extern crate proc_macro;
>     use proc_macro::TokenStream;

>     #[proc_macro]
>     pub fn make_answer(_item: TokenStream) -> TokenStream {
>         "fn answer() -> u32 { 42 }".parse().unwrap()
>     }

> We can use it in a binary crate to print “42” to standard output.

>     extern crate proc_macro_examples;
>     use proc_macro_examples::make_answer;

>     make_answer!();

>     fn main() {
>         println!("{}", answer());
>     }

[macro.proc.proc_macro.syntax]

The `proc_macro` attribute uses the MetaWord syntax.

[macro.proc.proc_macro.allowed-positions]

The `proc_macro` attribute may only be applied to a `pub` function of type `fn(TokenStream) -> TokenStream` where `TokenStream` comes from the `proc_macro` crate. It must have the “Rust” ABI. No other function qualifiers are allowed. It must be located in the root of the crate.

[macro.proc.proc_macro.duplicates]

The `proc_macro` attribute may only be specified once on a function.

[macro.proc.proc_macro.namespace]

The `proc_macro` attribute publicly defines the macro in the macro namespace in the root of the crate with the same name as the function.

[macro.proc.proc_macro.behavior]

A function-like macro invocation of a function-like procedural macro will pass what is inside the delimiters of the macro invocation as the input `TokenStream` argument and replace the entire macro invocation with the output `TokenStream` of the function.

[macro.proc.proc_macro.invocation]

Function-like procedural macros may be invoked in any macro invocation position, which includes:

- Statements
- Expressions
- Patterns
- Type expressions
- Item positions, including items in `extern` blocks
- Inherent and trait implementations
- Trait definitions

[macro.proc.derive]

## The `proc_macro_derive` attribute

[macro.proc.derive.intro]

Applying the `proc_macro_derive` attribute to a function defines a derive macro that can be invoked by the `derive` attribute. These macros are given the token stream of a struct, enum, or union definition and can emit new items after it. They can also declare and use derive macro helper attributes.

> Example

> This derive macro ignores its input and appends tokens that define a function.

>     #![crate_type = "proc-macro"]
>     extern crate proc_macro;
>     use proc_macro::TokenStream;

>     #[proc_macro_derive(AnswerFn)]
>     pub fn derive_answer_fn(_item: TokenStream) -> TokenStream {
>         "fn answer() -> u32 { 42 }".parse().unwrap()
>     }

> To use it, we might write:

>     extern crate proc_macro_examples;
>     use proc_macro_examples::AnswerFn;

>     #[derive(AnswerFn)]
>     struct Struct;

>     fn main() {
>         assert_eq!(42, answer());
>     }

[macro.proc.derive.syntax]

The syntax for the `proc_macro_derive` attribute is:

Syntax
ProcMacroDeriveAttribute →
proc_macro_derive ( DeriveMacroName ( , DeriveMacroAttributes )? ,? )

DeriveMacroName → IDENTIFIER

DeriveMacroAttributes →
attributes ( ( IDENTIFIER ( , IDENTIFIER )* ,? )? )

The name of the derive macro is given by DeriveMacroName. The optional `attributes` argument is described in macro.proc.derive.attributes.

[macro.proc.derive.allowed-positions]

The `proc_macro_derive` attribute may only be applied to a `pub` function with the Rust ABI defined in the root of the crate with a type of `fn(TokenStream) -> TokenStream` where `TokenStream` comes from the `proc_macro` crate. The function may be `const` and may use `extern` to explicitly specify the Rust ABI, but it may not use any other qualifiers (e.g. it may not be `async` or `unsafe`).

[macro.proc.derive.duplicates]

The `proc_macro_derive` attribute may be used only once on a function.

[macro.proc.derive.namespace]

The `proc_macro_derive` attribute publicly defines the derive macro in the macro namespace in the root of the crate.

[macro.proc.derive.output]

The input `TokenStream` is the token stream of the item to which the `derive` attribute is applied. The output `TokenStream` must be a (possibly empty) set of items. These items are appended following the input item within the same module or block.

[macro.proc.derive.attributes]

### Derive macro helper attributes

[macro.proc.derive.attributes.intro]

Derive macros can declare derive macro helper attributes to be used within the scope of the item to which the derive macro is applied. These attributes are inert. While their purpose is to be used by the macro that declared them, they can be seen by any macro.

[macro.proc.derive.attributes.decl]

A helper attribute for a derive macro is declared by adding its identifier to the `attributes` list in the `proc_macro_derive` attribute.

> Example

> This declares a helper attribute and then ignores it.

>     #![crate_type="proc-macro"]
>     extern crate proc_macro;
>     use proc_macro::TokenStream;

>     #[proc_macro_derive(WithHelperAttr, attributes(helper))]
>     pub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream {
>         TokenStream::new()
>     }

> To use it, we might write:

>     #[derive(WithHelperAttr)]
>     struct Struct {
>         #[helper] field: (),
>     }

[macro.proc.derive.attributes.scope]

When a derive macro invocation is applied to an item, the helper attributes introduced by that derive macro become in scope 1) for attributes that are applied to that item and are applied lexically after the derive macro invocation and 2) for attributes that are applied to fields and variants inside of the item.

> Note

> rustc currently allows derive helpers to be used before the macro that introduces them. Such derive helpers used out of order may not shadow other attribute macros. This behavior is deprecated and slated for removal.

>     #[helper] // Deprecated, hard error in the future.
>     #[derive(WithHelperAttr)]
>     struct Struct {
>         field: (),
>     }

> For more details, see Rust issue #79202.

[macro.proc.attribute]

## The `proc_macro_attribute` attribute

[macro.proc.attribute.intro]

The `proc_macro_attribute` attribute defines an attribute macro which can be used as an outer attribute.

> Example

> This attribute macro takes the input stream and emits it as-is, effectively being a no-op attribute.

>     #![crate_type = "proc-macro"]
>     extern crate proc_macro;
>     use proc_macro::TokenStream;

>     #[proc_macro_attribute]
>     pub fn return_as_is(_attr: TokenStream, item: TokenStream) -> TokenStream {
>         item
>     }

> Example

> This shows, in the output of the compiler, the stringified `TokenStream`s that attribute macros see.

>     // my-macro/src/lib.rs
>     extern crate proc_macro;
>     use proc_macro::TokenStream;
>     #[proc_macro_attribute]
>     pub fn show_streams(attr: TokenStream, item: TokenStream) -> TokenStream {
>         println!("attr: \"{attr}\"");
>         println!("item: \"{item}\"");
>         item
>     }

>     // src/lib.rs
>     extern crate my_macro;

>     use my_macro::show_streams;

>     // Example: Basic function.
>     #[show_streams]
>     fn invoke1() {}
>     // out: attr: ""
>     // out: item: "fn invoke1() {}"

>     // Example: Attribute with input.
>     #[show_streams(bar)]
>     fn invoke2() {}
>     // out: attr: "bar"
>     // out: item: "fn invoke2() {}"

>     // Example: Multiple tokens in the input.
>     #[show_streams(multiple => tokens)]
>     fn invoke3() {}
>     // out: attr: "multiple => tokens"
>     // out: item: "fn invoke3() {}"

>     // Example: Delimiters in the input.
>     #[show_streams { delimiters }]
>     fn invoke4() {}
>     // out: attr: "delimiters"
>     // out: item: "fn invoke4() {}"

[macro.proc.attribute.syntax]

The `proc_macro_attribute` attribute uses the MetaWord syntax.

[macro.proc.attribute.allowed-positions]

The `proc_macro_attribute` attribute may only be applied to a `pub` function of type `fn(TokenStream, TokenStream) -> TokenStream` where `TokenStream` comes from the `proc_macro` crate. It must have the “Rust” ABI. No other function qualifiers are allowed. It must be located in the root of the crate.

[macro.proc.attribute.duplicates]

The `proc_macro_attribute` attribute may only be specified once on a function.

[macro.proc.attribute.namespace]

The `proc_macro_attribute` attribute defines the attribute in the macro namespace in the root of the crate with the same name as the function.

[macro.proc.attribute.use-positions]

Attribute macros can only be used on:

- Items
- Items in `extern` blocks
- Inherent and trait implementations
- Trait definitions

[macro.proc.attribute.behavior]

The first `TokenStream` parameter is the delimited token tree following the attribute’s name but not including the outer delimiters. If the applied attribute contains only the attribute name or the attribute name followed by empty delimiters, the `TokenStream` is empty.

The second `TokenStream` is the rest of the item, including other attributes on the item.

The item to which the attribute is applied is replaced by the zero or more items in the returned `TokenStream`.

[macro.proc.token]

## Declarative macro tokens and procedural macro tokens

[macro.proc.token.intro]

Declarative `macro_rules` macros and procedural macros use similar, but different definitions for tokens (or rather `TokenTree`s.)

[macro.proc.token.macro_rules]

Token trees in `macro_rules` (corresponding to `tt` matchers) are defined as

- Delimited groups (`(...)`, `{...}`, etc)
- All operators supported by the language, both single-character and multi-character ones (`+`, `+=`).
  - Note that this set doesn’t include the single quote `'`.
- Literals (`"string"`, `1`, etc)
  - Note that negation (e.g. `-1`) is never a part of such literal tokens, but a separate operator token.
- Identifiers, including keywords (`ident`, `r#ident`, `fn`)
- Lifetimes (`'ident`)
- Metavariable substitutions in `macro_rules` (e.g. `$my_expr` in `macro_rules! mac { ($my_expr: expr) => { $my_expr } }` after the `mac`’s expansion, which will be considered a single token tree regardless of the passed expression)

[macro.proc.token.tree]

Token trees in procedural macros are defined as

- Delimited groups (`(...)`, `{...}`, etc)
- All punctuation characters used in operators supported by the language (`+`, but not `+=`), and also the single quote `'` character (typically used in lifetimes, see below for lifetime splitting and joining behavior)
- Literals (`"string"`, `1`, etc)
  - Negation (e.g. `-1`) is supported as a part of integer and floating point literals.
- Identifiers, including keywords (`ident`, `r#ident`, `fn`)

[macro.proc.token.conversion.intro]

Mismatches between these two definitions are accounted for when token streams are passed to and from procedural macros.
Note that the conversions below may happen lazily, so they might not happen if the tokens are not actually inspected.

[macro.proc.token.conversion.to-proc_macro]

When passed to a proc-macro

- All multi-character operators are broken into single characters.
- Lifetimes are broken into a `'` character and an identifier.
- The keyword metavariable `$crate` is passed as a single identifier.
- All other metavariable substitutions are represented as their underlying token streams.
  - Such token streams may be wrapped into delimited groups (`Group`) with implicit delimiters (`Delimiter::None`) when it’s necessary for preserving parsing priorities.
  - `tt` and `ident` substitutions are never wrapped into such groups and always represented as their underlying token trees.

[macro.proc.token.conversion.from-proc_macro]

When emitted from a proc macro

- Punctuation characters are glued into multi-character operators when applicable.
- Single quotes `'` joined with identifiers are glued into lifetimes.
- Negative literals are converted into two tokens (the `-` and the literal) possibly wrapped into a delimited group (`Group`) with implicit delimiters (`Delimiter::None`) when it’s necessary for preserving parsing priorities.

[macro.proc.token.doc-comment]

Note that neither declarative nor procedural macros support doc comment tokens (e.g. `/// Doc`), so they are always converted to token streams representing their equivalent `#[doc = r"str"]` attributes when passed to macros.

[crate]

# Crates and source files

[crate.syntax]

Syntax
Crate →
InnerAttribute*
Item*

> Note

> Although Rust, like any other language, can be implemented by an interpreter as well as a compiler, the only existing implementation is a compiler, and the language has always been designed to be compiled. For these reasons, this section assumes a compiler.

[crate.compile-time]

Rust’s semantics obey a phase distinction between compile-time and run-time.1 Semantic rules that have a static interpretation govern the success or failure of compilation, while semantic rules that have a dynamic interpretation govern the behavior of the program at run-time.

[crate.unit]

The compilation model centers on artifacts called crates. Each compilation processes a single crate in source form, and if successful, produces a single crate in binary form: either an executable or some sort of library.2

[crate.module]

A crate is a unit of compilation and linking, as well as versioning, distribution, and runtime loading. A crate contains a tree of nested module scopes. The top level of this tree is a module that is anonymous (from the point of view of paths within the module) and any item within a crate has a canonical module path denoting its location within the crate’s module tree.

[crate.input-source]

The Rust compiler is always invoked with a single source file as input, and always produces a single output crate. The processing of that source file may result in other source files being loaded as modules. Source files have the extension `.rs`.

[crate.module-def]

A Rust source file describes a module, the name and location of which — in the module tree of the current crate — are defined from outside the source file: either by an explicit Module item in a referencing source file, or by the name of the crate itself.

[crate.inline-module]

Every source file is a module, but not every module needs its own source file: module definitions can be nested within one file.

[crate.items]

Each source file contains a sequence of zero or more Item definitions, and may optionally begin with any number of attributes that apply to the containing module, most of which influence the behavior of the compiler.

[crate.attributes]

The anonymous crate module can have additional attributes that apply to the crate as a whole.

> Note

> The file’s contents may be preceded by a shebang.

    #![allow(unused)]
    fn main() {
    // Specify the crate name.
    #![crate_name = "projx"]

    // Specify the type of output artifact.
    #![crate_type = "lib"]

    // Turn on a warning.
    // This can be done in any module, not just the anonymous crate module.
    #![warn(non_camel_case_types)]
    }

[crate.main]

## Main functions

[crate.main.general]

A crate that contains a `main` function can be compiled to an executable.

[crate.main.restriction]

If a `main` function is present, it must take no arguments, must not declare any trait or lifetime bounds, must not have any where clauses, and its return type must implement the `Termination` trait.

    fn main() {}

    fn main() -> ! {
        std::process::exit(0);
    }

    fn main() -> impl std::process::Termination {
        std::process::ExitCode::SUCCESS
    }

[crate.main.import]

The `main` function may be an import, e.g. from an external crate or from the current one.

    #![allow(unused)]
    fn main() {
    mod foo {
        pub fn bar() {
            println!("Hello, world!");
        }
    }
    use foo::bar as main;
    }

> Note

> Types with implementations of `Termination` in the standard library include:

> - `()`
> - `!`
> - `Infallible`
> - `ExitCode`
> - `Result<T, E> where T: Termination, E: Debug`

[crate.uncaught-foreign-unwinding]

### Uncaught foreign unwinding

When a “foreign” unwind (e.g. an exception thrown from C++ code, or a `panic!` in Rust code using a different panic handler) propagates beyond the `main` function, the process will be safely terminated. This may take the form of an abort, in which case it is not guaranteed that any `Drop` calls will be executed, and the error output may be less informative than if the runtime had been terminated by a “native” Rust `panic`.

For more information, see the panic documentation.

[crate.no_main]

### The `no_main` attribute

The `no_main` attribute may be applied at the crate level to disable emitting the `main` symbol for an executable binary. This is useful when some other object being linked to defines `main`.

[crate.crate_name]

## The `crate_name` attribute

[crate.crate_name.general]

The `crate_name` attribute may be applied at the crate level to specify the name of the crate with the MetaNameValueStr syntax.

    #![allow(unused)]
    #![crate_name = "mycrate"]
    fn main() {
    }

[crate.crate_name.restriction]

The crate name must not be empty, and must only contain Unicode alphanumeric or `_` (U+005F) characters.

1. This distinction would also exist in an interpreter. Static checks like syntactic analysis, type checking, and lints should happen before the program is executed regardless of when it is executed. ↩

2. A crate is somewhat analogous to an assembly in the ECMA-335 CLI model, a library in the SML/NJ Compilation Manager, a unit in the Owens and Flatt module system, or a configuration in Mesa. ↩

[cfg]

# Conditional compilation

[cfg.syntax]

Syntax
ConfigurationPredicate →
ConfigurationOption
| ConfigurationAll
| ConfigurationAny
| ConfigurationNot
| true
| false

ConfigurationOption →
IDENTIFIER ( = ( STRING_LITERAL | RAW_STRING_LITERAL ) )?

ConfigurationAll →
all ( ConfigurationPredicateList? )

ConfigurationAny →
any ( ConfigurationPredicateList? )

ConfigurationNot →
not ( ConfigurationPredicate )

ConfigurationPredicateList →
ConfigurationPredicate ( , ConfigurationPredicate )* ,?

[cfg.general]

Conditionally compiled source code is source code that is compiled only under certain conditions.

[cfg.attributes-macro]

Source code can be made conditionally compiled using the `cfg` and `cfg_attr` attributes and the built-in `cfg` macro.

[cfg.conditional]

Whether to compile can depend on the target architecture of the compiled crate, arbitrary values passed to the compiler, and other things further described below.

[cfg.predicate]

Each form of conditional compilation takes a configuration predicate that evaluates to true or false. The predicate is one of the following:

[cfg.predicate.option]

- A configuration option. The predicate is true if the option is set, and false if it is unset.

[cfg.predicate.all]

- `all()` with a comma-separated list of configuration predicates. It is true if all of the given predicates are true, or if the list is empty.

[cfg.predicate.any]

- `any()` with a comma-separated list of configuration predicates. It is true if at least one of the given predicates is true. If there are no predicates, it is false.

[cfg.predicate.not]

- `not()` with a configuration predicate. It is true if its predicate is false and false if its predicate is true.

[cfg.predicate.literal]

- `true` or `false` literals, which are always true or false respectively.

[cfg.option-spec]

Configuration options are either names or key-value pairs, and are either set or unset.

[cfg.option-name]

Names are written as a single identifier, such as `unix`.

[cfg.option-key-value]

Key-value pairs are written as an identifier, `=`, and then a string, such as `target_arch = "x86_64"`.

> Note

> Whitespace around the `=` is ignored, so `foo="bar"` and `foo = "bar"` are equivalent.

[cfg.option-key-uniqueness]

Keys do not need to be unique. For example, both `feature = "std"` and `feature = "serde"` can be set at the same time.

[cfg.options.set]

## Set configuration options

[cfg.options.general]

Which configuration options are set is determined statically during the compilation of the crate.

[cfg.options.target]

Some options are compiler-set based on data about the compilation.

[cfg.options.other]

Other options are arbitrarily-set based on input passed to the compiler outside of the code.

[cfg.options.crate]

It is not possible to set a configuration option from within the source code of the crate being compiled.

> Note

> For `rustc`, arbitrary-set configuration options are set using the `--cfg` flag. Configuration values for a specified target can be displayed with `rustc --print cfg --target $TARGET`.

> Note

> Configuration options with the key `feature` are a convention used by Cargo for specifying compile-time options and optional dependencies.

[cfg.target_arch]

### `target_arch`

[cfg.target_arch.gen]

Key-value option set once with the target’s CPU architecture. The value is similar to the first element of the platform’s target triple, but not identical.

[cfg.target_arch.values]

Example values:

- `"x86"`
- `"x86_64"`
- `"mips"`
- `"powerpc"`
- `"powerpc64"`
- `"arm"`
- `"aarch64"`

[cfg.target_feature]

### `target_feature`

[cfg.target_feature.general]

Key-value option set for each platform feature available for the current compilation target.

[cfg.target_feature.values]

Example values:

- `"avx"`
- `"avx2"`
- `"crt-static"`
- `"rdrand"`
- `"sse"`
- `"sse2"`
- `"sse4.1"`

See the `target_feature` attribute for more details on the available features.

[cfg.target_feature.crt_static]

An additional feature of `crt-static` is available to the `target_feature` option to indicate that a static C runtime is available.

[cfg.target_os]

### `target_os`

[cfg.target_os.general]

Key-value option set once with the target’s operating system. This value is similar to the second and third element of the platform’s target triple.

[cfg.target_os.values]

Example values:

- `"windows"`
- `"macos"`
- `"ios"`
- `"linux"`
- `"android"`
- `"freebsd"`
- `"dragonfly"`
- `"openbsd"`
- `"netbsd"`
- `"none"` (typical for embedded targets)

[cfg.target_family]

### `target_family`

[cfg.target_family.general]

Key-value option providing a more generic description of a target, such as the family of the operating systems or architectures that the target generally falls into. Any number of `target_family` key-value pairs can be set.

[cfg.target_family.values]

Example values:

- `"unix"`
- `"windows"`
- `"wasm"`
- Both `"unix"` and `"wasm"`

[cfg.target_family.unix]

### `unix` and `windows`

`unix` is set if `target_family = "unix"` is set.

[cfg.target_family.windows]

`windows` is set if `target_family = "windows"` is set.

[cfg.target_env]

### `target_env`

[cfg.target_env.general]

Key-value option set with further disambiguating information about the target platform with information about the ABI or `libc` used. For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty. This value is similar to the fourth element of the platform’s target triple. One difference is that embedded ABIs such as `gnueabihf` will simply define `target_env` as `"gnu"`.

[cfg.target_env.values]

Example values:

- `""`
- `"gnu"`
- `"msvc"`
- `"musl"`
- `"sgx"`
- `"sim"`
- `"macabi"`

[cfg.target_abi]

### `target_abi`

[cfg.target_abi.general]

Key-value option set to further disambiguate the target with information about the target ABI.

[cfg.target_abi.disambiguation]

For historical reasons, this value is only defined as not the empty-string when actually needed for disambiguation. Thus, for example, on many GNU platforms, this value will be empty.

[cfg.target_abi.values]

Example values:

- `""`
- `"llvm"`
- `"eabihf"`
- `"abi64"`

[cfg.target_endian]

### `target_endian`

Key-value option set once with either a value of “little” or “big” depending on the endianness of the target’s CPU.

[cfg.target_pointer_width]

### `target_pointer_width`

[cfg.target_pointer_width.general]

Key-value option set once with the target’s pointer width in bits.

[cfg.target_pointer_width.values]

Example values:

- `"16"`
- `"32"`
- `"64"`

[cfg.target_vendor]

### `target_vendor`

[cfg.target_vendor.general]

Key-value option set once with the vendor of the target.

[cfg.target_vendor.values]

Example values:

- `"apple"`
- `"fortanix"`
- `"pc"`
- `"unknown"`

[cfg.target_has_atomic]

### `target_has_atomic`

[cfg.target_has_atomic.general]

Key-value option set for each bit width that the target supports atomic loads, stores, and compare-and-swap operations.

[cfg.target_has_atomic.stdlib]

When this cfg is present, all of the stable `core::sync::atomic` APIs are available for the relevant atomic width.

[cfg.target_has_atomic.values]

Possible values:

- `"8"`
- `"16"`
- `"32"`
- `"64"`
- `"128"`
- `"ptr"`

[cfg.test]

### `test`

Enabled when compiling the test harness. Done with `rustc` by using the `--test` flag. See Testing for more on testing support.

[cfg.debug_assertions]

### `debug_assertions`

Enabled by default when compiling without optimizations. This can be used to enable extra debugging code in development but not in production. For example, it controls the behavior of the standard library’s `debug_assert!` macro.

[cfg.proc_macro]

### `proc_macro`

Set when the crate being compiled is being compiled with the `proc_macro` crate type.

[cfg.panic]

### `panic`

[cfg.panic.general]

Key-value option set depending on the panic strategy. Note that more values may be added in the future.

[cfg.panic.values]

Example values:

- `"abort"`
- `"unwind"`

## Forms of conditional compilation

[cfg.attr]

### The `cfg` attribute

[cfg.attr.intro]

The `cfg` attribute conditionally includes the form to which it is attached based on a configuration predicate.

> Example

>     #![allow(unused)]
>     fn main() {
>     // The function is only included in the build when compiling for macOS
>     #[cfg(target_os = "macos")]
>     fn macos_only() {
>       // ...
>     }

>     // This function is only included when either foo or bar is defined
>     #[cfg(any(foo, bar))]
>     fn needs_foo_or_bar() {
>       // ...
>     }

>     // This function is only included when compiling for a unixish OS with a 32-bit
>     // architecture
>     #[cfg(all(unix, target_pointer_width = "32"))]
>     fn on_32bit_unix() {
>       // ...
>     }

>     // This function is only included when foo is not defined
>     #[cfg(not(foo))]
>     fn needs_not_foo() {
>       // ...
>     }

>     // This function is only included when the panic strategy is set to unwind
>     #[cfg(panic = "unwind")]
>     fn when_unwinding() {
>       // ...
>     }
>     }

[cfg.attr.syntax]

The syntax for the `cfg` attribute is:

Syntax
CfgAttribute → cfg ( ConfigurationPredicate )

[cfg.attr.allowed-positions]

The `cfg` attribute may be used anywhere attributes are allowed.

[cfg.attr.duplicates]

The `cfg` attribute may be used any number of times on a form. The form to which the attributes are attached will not be included if any of the `cfg` predicates are false except as described in cfg.attr.crate-level-attrs.

[cfg.attr.effect]

If the predicates are true, the form is rewritten to not have the `cfg` attributes on it. If any predicate is false, the form is removed from the source code.

[cfg.attr.crate-level-attrs]

When a crate-level `cfg` has a false predicate, the crate itself still exists. Any crate attributes preceding the `cfg` are kept, and any crate attributes following the `cfg` are removed as well as removing all of the following crate contents.

> Example

> The behavior of not removing the preceding attributes allows you to do things such as include `#![no_std]` to avoid linking `std` even if a `#![cfg(...)]` has otherwise removed the contents of the crate. For example:

>     // This `no_std` attribute is kept even though the crate-level `cfg`
>     // attribute is false.
>     #![no_std]
>     #![cfg(false)]

>     // This function is not included.
>     pub fn example() {}

[cfg.cfg_attr]

### The `cfg_attr` attribute

[cfg.cfg_attr.intro]

The `cfg_attr` attribute conditionally includes attributes based on a configuration predicate.

> Example

> The following module will either be found at `linux.rs` or `windows.rs` based on the target.

>     #[cfg_attr(target_os = "linux", path = "linux.rs")]
>     #[cfg_attr(windows, path = "windows.rs")]
>     mod os;

[cfg.cfg_attr.syntax]

The syntax for the `cfg_attr` attribute is:

Syntax
CfgAttrAttribute → cfg_attr ( ConfigurationPredicate , CfgAttrs? )

CfgAttrs → Attr ( , Attr )* ,?

[cfg.cfg_attr.allowed-positions]

The `cfg_attr` attribute may be used anywhere attributes are allowed.

[cfg.cfg_attr.duplicates]

The `cfg_attr` attribute may be used any number of times on a form.

[cfg.cfg_attr.attr-restriction]

The `crate_type` and `crate_name` attributes cannot be used with `cfg_attr`.

[cfg.cfg_attr.behavior]

When the configuration predicate is true, `cfg_attr` expands out to the attributes listed after the predicate.

[cfg.cfg_attr.attribute-list]

Zero, one, or more attributes may be listed. Multiple attributes will each be expanded into separate attributes.

> Example

>     #[cfg_attr(feature = "magic", sparkles, crackles)]
>     fn bewitched() {}

>     // When the `magic` feature flag is enabled, the above will expand to:
>     #[sparkles]
>     #[crackles]
>     fn bewitched() {}

> Note

> The `cfg_attr` can expand to another `cfg_attr`. For example, `#[cfg_attr(target_os = "linux", cfg_attr(feature = "multithreaded", some_other_attribute))]` is valid. This example would be equivalent to `#[cfg_attr(all(target_os = "linux", feature = "multithreaded"), some_other_attribute)]`.

[cfg.macro]

### The `cfg` macro

The built-in `cfg` macro takes in a single configuration predicate and evaluates to the `true` literal when the predicate is true and the `false` literal when it is false.

For example:

    #![allow(unused)]
    fn main() {
    let machine_kind = if cfg!(unix) {
      "unix"
    } else if cfg!(windows) {
      "windows"
    } else {
      "unknown"
    };

    println!("I'm running on a {} machine!", machine_kind);
    }

[items]

# Items

[items.syntax]

Syntax
Item →
OuterAttribute* ( VisItem | MacroItem )

VisItem →
Visibility?
(
Module
| ExternCrate
| UseDeclaration
| Function
| TypeAlias
| Struct
| Enumeration
| Union
| ConstantItem
| StaticItem
| Trait
| Implementation
| ExternBlock
)

MacroItem →
MacroInvocationSemi
| MacroRulesDefinition

[items.intro]

An item is a component of a crate. Items are organized within a crate by a nested set of modules. Every crate has a single “outermost” anonymous module; all further items within the crate have paths within the module tree of the crate.

[items.static-def]

Items are entirely determined at compile-time, generally remain fixed during execution, and may reside in read-only memory.

[items.kinds]

There are several kinds of items:

- modules
- `extern crate` declarations
- `use` declarations
- function definitions
- type alias definitions
- struct definitions
- enumeration definitions
- union definitions
- constant items
- static items
- trait definitions
- implementations
- `extern` blocks

[items.locations]

Items may be declared in the root of the crate, a module, or a block expression.

[items.associated-locations]

A subset of items, called associated items, may be declared in traits and implementations.

[items.extern-locations]

A subset of items, called external items, may be declared in `extern` blocks.

[items.decl-order]

Items may be defined in any order, with the exception of `macro_rules` which has its own scoping behavior.

[items.name-resolution]

Name resolution of item names allows items to be defined before or after where the item is referred to in the module or block.

See item scopes for information on the scoping rules of items.

[items.mod]

# Modules

[items.mod.syntax]

Syntax
Module →
unsafe? mod IDENTIFIER ;
| unsafe? mod IDENTIFIER {
InnerAttribute*
Item*
}

[items.mod.intro]

A module is a container for zero or more items.

[items.mod.def]

A module item is a module, surrounded in braces, named, and prefixed with the keyword `mod`. A module item introduces a new, named module into the tree of modules making up a crate.

[items.mod.nesting]

Modules can nest arbitrarily.

An example of a module:

    #![allow(unused)]
    fn main() {
    mod math {
        type Complex = (f64, f64);
        fn sin(f: f64) -> f64 {
            /* ... */
          unimplemented!();
        }
        fn cos(f: f64) -> f64 {
            /* ... */
          unimplemented!();
        }
        fn tan(f: f64) -> f64 {
            /* ... */
          unimplemented!();
        }
    }
    }

[items.mod.namespace]

Modules are defined in the type namespace of the module or block where they are located.

[items.mod.multiple-items]

It is an error to define multiple items with the same name in the same namespace within a module. See the scopes chapter for more details on restrictions and shadowing behavior.

[items.mod.unsafe]

The `unsafe` keyword is syntactically allowed to appear before the `mod` keyword, but it is rejected at a semantic level. This allows macros to consume the syntax and make use of the `unsafe` keyword, before removing it from the token stream.

[items.mod.outlined]

## Module source filenames

[items.mod.outlined.intro]

A module without a body is loaded from an external file. When the module does not have a `path` attribute, the path to the file mirrors the logical module path.

[items.mod.outlined.search]

Ancestor module path components are directories, and the module’s contents are in a file with the name of the module plus the `.rs` extension. For example, the following module structure can have this corresponding filesystem structure:

Module Path | Filesystem Path | File Contents
--- | --- | ---
`crate` | `lib.rs` | `mod util;`
`crate::util` | `util.rs` | `mod config;`
`crate::util::config` | `util/config.rs` |

[items.mod.outlined.search-mod]

Module filenames may also be the name of the module as a directory with the contents in a file named `mod.rs` within that directory. The above example can alternately be expressed with `crate::util`’s contents in a file named `util/mod.rs`. It is not allowed to have both `util.rs` and `util/mod.rs`.

> Note

> Prior to `rustc` 1.30, using `mod.rs` files was the way to load a module with nested children. It is encouraged to use the new naming convention as it is more consistent, and avoids having many files named `mod.rs` within a project.

[items.mod.outlined.path]

### The `path` attribute

[items.mod.outlined.path.intro]

The directories and files used for loading external file modules can be influenced with the `path` attribute.

[items.mod.outlined.path.search]

For `path` attributes on modules not inside inline module blocks, the file path is relative to the directory the source file is located. For example, the following code snippet would use the paths shown based on where it is located:

    #[path = "foo.rs"]
    mod c;

Source File | `c`’s File Location | `c`’s Module Path
--- | --- | ---
`src/a/b.rs` | `src/a/foo.rs` | `crate::a::b::c`
`src/a/mod.rs` | `src/a/foo.rs` | `crate::a::c`

[items.mod.outlined.path.search-nested]

For `path` attributes inside inline module blocks, the relative location of the file path depends on the kind of source file the `path` attribute is located in. “mod-rs” source files are root modules (such as `lib.rs` or `main.rs`) and modules with files named `mod.rs`. “non-mod-rs” source files are all other module files. Paths for `path` attributes inside inline module blocks in a mod-rs file are relative to the directory of the mod-rs file including the inline module components as directories. For non-mod-rs files, it is the same except the path starts with a directory with the name of the non-mod-rs module. For example, the following code snippet would use the paths shown based on where it is located:

    mod inline {
        #[path = "other.rs"]
        mod inner;
    }

Source File | `inner`’s File Location | `inner`’s Module Path
--- | --- | ---
`src/a/b.rs` | `src/a/b/inline/other.rs` | `crate::a::b::inline::inner`
`src/a/mod.rs` | `src/a/inline/other.rs` | `crate::a::inline::inner`

An example of combining the above rules of `path` attributes on inline modules and nested modules within (applies to both mod-rs and non-mod-rs files):

    #[path = "thread_files"]
    mod thread {
        // Load the `local_data` module from `thread_files/tls.rs` relative to
        // this source file's directory.
        #[path = "tls.rs"]
        mod local_data;
    }

[items.mod.attributes]

## Attributes on modules

[items.mod.attributes.intro]

Modules, like all items, accept outer attributes. They also accept inner attributes: either after `{` for a module with a body, or at the beginning of the source file, after the optional BOM and shebang.

[items.mod.attributes.supported]

The built-in attributes that have meaning on a module are `cfg`, `deprecated`, `doc`, the lint check attributes, `path`, and `no_implicit_prelude`. Modules also accept macro attributes.

[items.extern-crate]

# Extern crate declarations

[items.extern-crate.syntax]

Syntax
ExternCrate → extern crate CrateRef AsClause? ;

CrateRef → IDENTIFIER | self

AsClause → as ( IDENTIFIER | _ )

[items.extern-crate.intro]

An `extern crate` declaration specifies a dependency on an external crate.

[items.extern-crate.namespace]

The external crate is then bound into the declaring scope as the given identifier in the type namespace.

[items.extern-crate.extern-prelude]

Additionally, if the `extern crate` appears in the crate root, then the crate name is also added to the extern prelude, making it automatically in scope in all modules.

[items.extern-crate.as]

The `as` clause can be used to bind the imported crate to a different name.

[items.extern-crate.lookup]

The external crate is resolved to a specific `soname` at compile time, and a runtime linkage requirement to that `soname` is passed to the linker for loading at runtime. The `soname` is resolved at compile time by scanning the compiler’s library path and matching the optional `crate_name` provided against the `crate_name` attributes that were declared on the external crate when it was compiled. If no `crate_name` is provided, a default `name` attribute is assumed, equal to the identifier given in the `extern crate` declaration.

[items.extern-crate.self]

The `self` crate may be imported which creates a binding to the current crate. In this case the `as` clause must be used to specify the name to bind it to.

Three examples of `extern crate` declarations:

    extern crate pcre;

    extern crate std; // equivalent to: extern crate std as std;

    extern crate std as ruststd; // linking to 'std' under another name

[items.extern-crate.name-restrictions]

When naming Rust crates, hyphens are disallowed. However, Cargo packages may make use of them. In such case, when `Cargo.toml` doesn’t specify a crate name, Cargo will transparently replace `-` with `_` (Refer to RFC 940 for more details).

Here is an example:

    // Importing the Cargo package hello-world
    extern crate hello_world; // hyphen replaced with an underscore

[items.extern-crate.underscore]

## Underscore imports

[items.extern-crate.underscore.intro]

An external crate dependency can be declared without binding its name in scope by using an underscore with the form `extern crate foo as _`. This may be useful for crates that only need to be linked, but are never referenced, and will avoid being reported as unused.

[items.extern-crate.underscore.macro_use]

The `macro_use` attribute works as usual and imports the macro names into the `macro_use` prelude.

[items.extern-crate.no_link]

## The `no_link` attribute

[items.extern-crate.no_link.intro]

The `no_link` attribute may be applied to an `extern crate` item to prevent linking the crate.

> Note

> This is helpful, e.g., when only the macros of a crate are needed.

> Example

>     #[no_link]
>     extern crate other_crate;

>     other_crate::some_macro!();

[items.extern-crate.no_link.syntax]

The `no_link` attribute uses the MetaWord syntax.

[items.extern-crate.no_link.allowed-positions]

The `no_link` attribute may only be applied to an `extern crate` declaration.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[items.extern-crate.no_link.duplicates]

Only the first use of `no_link` on an `extern crate` declaration has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[items.use]

# Use declarations

[items.use.syntax]

Syntax
UseDeclaration → use UseTree ;

UseTree →
( SimplePath? :: )? *
| ( SimplePath? :: )? { ( UseTree ( , UseTree )* ,? )? }
| SimplePath ( as ( IDENTIFIER | _ ) )?

[items.use.intro]

A use declaration creates one or more local name bindings synonymous with some other path. Usually a `use` declaration is used to shorten the path required to refer to a module item. These declarations may appear in modules and blocks, usually at the top. A `use` declaration is also sometimes called an import, or, if it is public, a re-export.

[items.use.forms]

Use declarations support a number of convenient shortcuts:

[items.use.forms.multiple]

- Simultaneously binding a list of paths with a common prefix, using the brace syntax `use a::b::{c, d, e::f, g::h::i};`

[items.use.forms.self]

- Simultaneously binding a list of paths with a common prefix and their common parent module, using the `self` keyword, such as `use a::b::{self, c, d::e};`

[items.use.forms.as]

- Rebinding the target name as a new local name, using the syntax `use p::q::r as x;`. This can also be used with the last two features: `use a::b::{self as ab, c as abc}`.

[items.use.forms.glob]

- Binding all paths matching a given prefix, using the asterisk wildcard syntax `use a::b::*;`.

[items.use.forms.nesting]

- Nesting groups of the previous features multiple times, such as `use a::b::{self as ab, c, d::{*, e::f}};`

An example of `use` declarations:

    use std::collections::hash_map::{self, HashMap};

    fn foo<T>(_: T){}
    fn bar(map1: HashMap<String, usize>, map2: hash_map::HashMap<String, usize>){}

    fn main() {
        // use declarations can also exist inside of functions
        use std::option::Option::{Some, None};

        // Equivalent to 'foo(vec![std::option::Option::Some(1.0f64),
        // std::option::Option::None]);'
        foo(vec![Some(1.0f64), None]);

        // Both `hash_map` and `HashMap` are in scope.
        let map1 = HashMap::new();
        let map2 = hash_map::HashMap::new();
        bar(map1, map2);
    }

[items.use.visibility]

## `use` Visibility

[items.use.visibility.intro]

Like items, `use` declarations are private to the containing module, by default. Also like items, a `use` declaration can be public, if qualified by the `pub` keyword. Such a `use` declaration serves to re-export a name. A public `use` declaration can therefore redirect some public name to a different target definition: even a definition with a private canonical path, inside a different module.

[items.use.visibility.unambiguous]

If a sequence of such redirections form a cycle or cannot be resolved unambiguously, they represent a compile-time error.

An example of re-exporting:

    mod quux {
        pub use self::foo::{bar, baz};
        pub mod foo {
            pub fn bar() {}
            pub fn baz() {}
        }
    }

    fn main() {
        quux::bar();
        quux::baz();
    }

In this example, the module `quux` re-exports two public names defined in `foo`.

[items.use.path]

## `use` Paths

[items.use.path.intro]

The paths that are allowed in a `use` item follow the SimplePath grammar and are similar to the paths that may be used in an expression. They may create bindings for:

- Nameable items
- Enum variants
- Built-in types
- Attributes
- Derive macros
- `macro_rules`

[items.use.path.disallowed]

They cannot import associated items, generic parameters, local variables, paths with `Self`, or tool attributes. More restrictions are described below.

[items.use.path.namespace]

`use` will create bindings for all namespaces from the imported entities, with the exception that a `self` import will only import from the type namespace (as described below). For example, the following illustrates creating bindings for the same name in two namespaces:

    #![allow(unused)]
    fn main() {
    mod stuff {
        pub struct Foo(pub i32);
    }

    // Imports the `Foo` type and the `Foo` constructor.
    use stuff::Foo;

    fn example() {
        let ctor = Foo; // Uses `Foo` from the value namespace.
        let x: Foo = ctor(123); // Uses `Foo` From the type namespace.
    }
    }

[items.use.path.edition2018]

> 2018 Edition differences

> In the 2015 edition, `use` paths are relative to the crate root. For example:

>     mod foo {
>         pub mod example { pub mod iter {} }
>         pub mod baz { pub fn foobaz() {} }
>     }
>     mod bar {
>         // Resolves `foo` from the crate root.
>         use foo::example::iter;
>         // The `::` prefix explicitly resolves `foo`
>         // from the crate root.
>         use ::foo::baz::foobaz;
>     }

>     fn main() {}

> The 2015 edition does not allow use declarations to reference the extern prelude. Thus, `extern crate` declarations are still required in 2015 to reference an external crate in a `use` declaration. Beginning with the 2018 edition, `use` declarations can specify an external crate dependency the same way `extern crate` can.

[items.use.as]

## `as` renames

The `as` keyword can be used to change the name of an imported entity. For example:

    #![allow(unused)]
    fn main() {
    // Creates a non-public alias `bar` for the function `foo`.
    use inner::foo as bar;

    mod inner {
        pub fn foo() {}
    }
    }

[items.use.multiple-syntax]

## Brace syntax

[items.use.multiple-syntax.intro]

Braces can be used in the last segment of the path to import multiple entities from the previous segment, or, if there are no previous segments, from the current scope. Braces can be nested, creating a tree of paths, where each grouping of segments is logically combined with its parent to create a full path.

    #![allow(unused)]
    fn main() {
    // Creates bindings to:
    // - `std::collections::BTreeSet`
    // - `std::collections::hash_map`
    // - `std::collections::hash_map::HashMap`
    use std::collections::{BTreeSet, hash_map::{self, HashMap}};
    }

[items.use.multiple-syntax.empty]

An empty brace does not import anything, though the leading path is validated that it is accessible.

[items.use.multiple-syntax.edition2018]

> 2018 Edition differences

> In the 2015 edition, paths are relative to the crate root, so an import such as `use {foo, bar};` will import the names `foo` and `bar` from the crate root, whereas starting in 2018, those names are relative to the current scope.

[items.use.self]

## `self` imports

[items.use.self.intro]

The keyword `self` may be used within brace syntax to create a binding of the parent entity under its own name.

    mod stuff {
        pub fn foo() {}
        pub fn bar() {}
    }
    mod example {
        // Creates a binding for `stuff` and `foo`.
        use crate::stuff::{self, foo};
        pub fn baz() {
            foo();
            stuff::bar();
        }
    }
    fn main() {}

[items.use.self.namespace]

`self` only creates a binding from the type namespace of the parent entity. For example, in the following, only the `foo` mod is imported:

    mod bar {
        pub mod foo {}
        pub fn foo() {}
    }

    // This only imports the module `foo`. The function `foo` lives in
    // the value namespace and is not imported.
    use bar::foo::{self};

    fn main() {
        foo(); //~ ERROR `foo` is a module
    }

> Note

> `self` may also be used as the first segment of a path. The usage of `self` as the first segment and inside a `use` brace is logically the same; it means the current module of the parent segment, or the current module if there is no parent segment. See `self` in the paths chapter for more information on the meaning of a leading `self`.

[items.use.glob]

## Glob imports

[items.use.glob.intro]

The `*` character may be used as the last segment of a `use` path to import all importable entities from the entity of the preceding segment. For example:

    #![allow(unused)]
    fn main() {
    // Creates a non-public alias to `bar`.
    use foo::*;

    mod foo {
        fn i_am_private() {}
        enum Example {
            V1,
            V2,
        }
        pub fn bar() {
            // Creates local aliases to `V1` and `V2`
            // of the `Example` enum.
            use Example::*;
            let x = V1;
        }
    }
    }

[items.use.glob.shadowing]

Items and named imports are allowed to shadow names from glob imports in the same namespace. That is, if there is a name already defined by another item in the same namespace, the glob import will be shadowed. For example:

    #![allow(unused)]
    fn main() {
    // This creates a binding to the `clashing::Foo` tuple struct
    // constructor, but does not import its type because that would
    // conflict with the `Foo` struct defined here.
    //
    // Note that the order of definition here is unimportant.
    use clashing::*;
    struct Foo {
        field: f32,
    }

    fn do_stuff() {
        // Uses the constructor from `clashing::Foo`.
        let f1 = Foo(123);
        // The struct expression uses the type from
        // the `Foo` struct defined above.
        let f2 = Foo { field: 1.0 };
        // `Bar` is also in scope due to the glob import.
        let z = Bar {};
    }

    mod clashing {
        pub struct Foo(pub i32);
        pub struct Bar {}
    }
    }

> Note

> For areas where shadowing is not allowed, see name resolution ambiguities.

[items.use.glob.last-segment-only]

`*` cannot be used as the first or intermediate segments.

[items.use.glob.self-import]

`*` cannot be used to import a module’s contents into itself (such as `use self::*;`).

[items.use.glob.edition2018]

> 2018 Edition differences

> In the 2015 edition, paths are relative to the crate root, so an import such as `use *;` is valid, and it means to import everything from the crate root. This cannot be used in the crate root itself.

[items.use.as-underscore]

## Underscore imports

[items.use.as-underscore.intro]

Items can be imported without binding to a name by using an underscore with the form `use path as _`. This is particularly useful to import a trait so that its methods may be used without importing the trait’s symbol, for example if the trait’s symbol may conflict with another symbol. Another example is to link an external crate without importing its name.

[items.use.as-underscore.glob]

Asterisk glob imports will import items imported with `_` in their unnameable form.

    mod foo {
        pub trait Zoo {
            fn zoo(&self) {}
        }

        impl<T> Zoo for T {}
    }

    use self::foo::Zoo as _;
    struct Zoo;  // Underscore import avoids name conflict with this item.

    fn main() {
        let z = Zoo;
        z.zoo();
    }

[items.use.as-underscore.macro]

The unique, unnameable symbols are created after macro expansion so that macros may safely emit multiple references to `_` imports. For example, the following should not produce an error:

    #![allow(unused)]
    fn main() {
    macro_rules! m {
        ($item: item) => { $item $item }
    }

    m!(use std as _;);
    // This expands to:
    // use std as _;
    // use std as _;
    }

[items.use.restrictions]

## Restrictions

The following are restrictions for valid `use` declarations:

[items.use.restrictions.crate]

- `use crate;` must use `as` to define the name to which to bind the crate root.

[items.use.restrictions.self]

- `use {self};` is an error; there must be a leading segment when using `self`.

[items.use.restrictions.duplicate-name]

- As with any item definition, `use` imports cannot create duplicate bindings of the same name in the same namespace in a module or block.

[items.use.restrictions.macro-crate]

- `use` paths with `$crate` are not allowed in a `macro_rules` expansion.

[items.use.restrictions.variant]

- `use` paths cannot refer to enum variants through a type alias. For example:

      #![allow(unused)]
      fn main() {
      enum MyEnum {
          MyVariant
      }
      type TypeAlias = MyEnum;

      use MyEnum::MyVariant; //~ OK
      use TypeAlias::MyVariant; //~ ERROR
      }

[items.fn]

# Functions

[items.fn.syntax]

Syntax
Function →
FunctionQualifiers fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
( BlockExpression | ; )

FunctionQualifiers → const? async?​1 ItemSafety?​2 ( extern Abi? )?

ItemSafety → safe​3 | unsafe

Abi → STRING_LITERAL | RAW_STRING_LITERAL

FunctionParameters →
SelfParam ,?
| ( SelfParam , )? FunctionParam ( , FunctionParam )* ,?

SelfParam → OuterAttribute* ( ShorthandSelf | TypedSelf )

ShorthandSelf → ( & | & Lifetime )? mut? self

TypedSelf → mut? self : Type

FunctionParam → OuterAttribute* ( FunctionParamPattern | ... | Type​4 )

FunctionParamPattern → PatternNoTopAlt : ( Type | ... )

FunctionReturnType → -> Type

[items.fn.intro]

A function consists of a block (that’s the body of the function), along with a name, a set of parameters, and an output type. Other than a name, all these are optional.

[items.fn.namespace]

Functions are declared with the keyword `fn` which defines the given name in the value namespace of the module or block where it is located.

[items.fn.signature]

Functions may declare a set of input variables as parameters, through which the caller passes arguments into the function, and the output type of the value the function will return to its caller on completion.

[items.fn.implicit-return]

If the output type is not explicitly stated, it is the unit type.

[items.fn.fn-item-type]

When referred to, a function yields a first-class value of the corresponding zero-sized function item type, which when called evaluates to a direct call to the function.

For example, this is a simple function:

    #![allow(unused)]
    fn main() {
    fn answer_to_life_the_universe_and_everything() -> i32 {
        return 42;
    }
    }

[items.fn.safety-qualifiers]

The `safe` function is semantically only allowed when used in an `extern` block.

[items.fn.params]

## Function parameters

[items.fn.params.intro]

Function parameters are irrefutable patterns, so any pattern that is valid in an else-less `let` binding is also valid as a parameter:

    #![allow(unused)]
    fn main() {
    fn first((value, _): (i32, i32)) -> i32 { value }
    }

[items.fn.params.self-pat]

If the first parameter is a SelfParam, this indicates that the function is a method.

[items.fn.params.self-restriction]

Functions with a self parameter may only appear as an associated function in a trait or implementation.

[items.fn.params.varargs]

A parameter with the `...` token indicates a variadic function, and may only be used as the last parameter of an external block function. The variadic parameter may have an optional identifier, such as `args: ...`.

[items.fn.body]

## Function body

[items.fn.body.intro]

The body block of a function is conceptually wrapped in another block that first binds the argument patterns and then `return`s the value of the function’s body. This means that the tail expression of the block, if evaluated, ends up being returned to the caller. As usual, an explicit return expression within the body of the function will short-cut that implicit return, if reached.

For example, the function above behaves as if it was written as:

    // argument_0 is the actual first argument passed from the caller
    let (value, _) = argument_0;
    return {
        value
    };

[items.fn.body.bodyless]

Functions without a body block are terminated with a semicolon. This form may only appear in a trait or external block.

[items.fn.generics]

## Generic functions

[items.fn.generics.intro]

A generic function allows one or more parameterized types to appear in its signature. Each type parameter must be explicitly declared in an angle-bracket-enclosed and comma-separated list, following the function name.

    #![allow(unused)]
    fn main() {
    // foo is generic over A and B

    fn foo<A, B>(x: A, y: B) {
    }
    }

[items.fn.generics.param-names]

Inside the function signature and body, the name of the type parameter can be used as a type name.

[items.fn.generics.param-bounds]

Trait bounds can be specified for type parameters to allow methods with that trait to be called on values of that type. This is specified using the `where` syntax:

    #![allow(unused)]
    fn main() {
    use std::fmt::Debug;
    fn foo<T>(x: T) where T: Debug {
    }
    }

[items.fn.generics.mono]

When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `foo` function here:

    #![allow(unused)]
    fn main() {
    use std::fmt::Debug;

    fn foo<T>(x: &[T]) where T: Debug {
        // details elided
    }

    foo(&[1, 2]);
    }

will instantiate type parameter `T` with `i32`.

[items.fn.generics.explicit-arguments]

The type parameters can also be explicitly supplied in a trailing path component after the function name. This might be necessary if there is not sufficient context to determine the type parameters. For example, `mem::size_of::<u32>() == 4`.

[items.fn.extern]

## Extern function qualifier

[items.fn.extern.intro]

The `extern` function qualifier allows providing function definitions that can be called with a particular ABI:

    extern "ABI" fn foo() { /* ... */ }

[items.fn.extern.def]

These are often used in combination with external block items which provide function declarations that can be used to call functions without providing their definition:

    unsafe extern "ABI" {
      unsafe fn foo(); /* no body */
      safe fn bar(); /* no body */
    }
    unsafe { foo() };
    bar();

[items.fn.extern.default-abi]

When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items, the ABI `"Rust"` is assigned. For example:

    #![allow(unused)]
    fn main() {
    fn foo() {}
    }

is equivalent to:

    #![allow(unused)]
    fn main() {
    extern "Rust" fn foo() {}
    }

[items.fn.extern.foreign-call]

Functions can be called by foreign code, and using an ABI that differs from Rust allows, for example, to provide functions that can be called from other programming languages like C:

    #![allow(unused)]
    fn main() {
    // Declares a function with the "C" ABI
    extern "C" fn new_i32() -> i32 { 0 }

    // Declares a function with the "stdcall" ABI
    #[cfg(any(windows, target_arch = "x86"))]
    extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
    }

[items.fn.extern.default-extern]

Just as with external block, when the `extern` keyword is used and the `"ABI"` is omitted, the ABI used defaults to `"C"`. That is, this:

    #![allow(unused)]
    fn main() {
    extern fn new_i32() -> i32 { 0 }
    let fptr: extern fn() -> i32 = new_i32;
    }

is equivalent to:

    #![allow(unused)]
    fn main() {
    extern "C" fn new_i32() -> i32 { 0 }
    let fptr: extern "C" fn() -> i32 = new_i32;
    }

[items.fn.extern.unwind]

### Unwinding

[items.fn.extern.unwind.intro]

Most ABI strings come in two variants, one with an `-unwind` suffix and one without. The `Rust` ABI always permits unwinding, so there is no `Rust-unwind` ABI. The choice of ABI, together with the runtime panic handler, determines the behavior when unwinding out of a function.

[items.fn.extern.unwind.behavior]

The table below indicates the behavior of an unwinding operation reaching each type of ABI boundary (function declaration or definition using the corresponding ABI string). Note that the Rust runtime is not affected by, and cannot have an effect on, any unwinding that occurs entirely within another language’s runtime, that is, unwinds that are thrown and caught without reaching a Rust ABI boundary.

The `panic`-unwind column refers to panicking via the `panic!` macro and similar standard library mechanisms, as well as to any other Rust operations that cause a panic, such as out-of-bounds array indexing or integer overflow.

The “unwinding” ABI category refers to `"Rust"` (the implicit ABI of Rust functions not marked `extern`), `"C-unwind"`, and any other ABI with `-unwind` in its name. The “non-unwinding” ABI category refers to all other ABI strings, including `"C"` and `"stdcall"`.

Native unwinding is defined per-target. On targets that support throwing and catching C++ exceptions, it refers to the mechanism used to implement this feature. Some platforms implement a form of unwinding referred to as “forced unwinding”; `longjmp` on Windows and `pthread_exit` in `glibc` are implemented this way. Forced unwinding is explicitly excluded from the “Native unwind” column in the table.

panic runtime | ABI | `panic`-unwind | Native unwind (unforced)
--- | --- | --- | ---
`panic=unwind` | unwinding | unwind | unwind
`panic=unwind` | non-unwinding | abort (see notes below) | undefined behavior
`panic=abort` | unwinding | `panic` aborts without unwinding | abort
`panic=abort` | non-unwinding | `panic` aborts without unwinding | undefined behavior

[items.fn.extern.abort]

With `panic=unwind`, when a `panic` is turned into an abort by a non-unwinding ABI boundary, either no destructors (`Drop` calls) will run, or all destructors up until the ABI boundary will run. It is unspecified which of those two behaviors will happen.

For other considerations and limitations regarding unwinding across FFI boundaries, see the relevant section in the Panic documentation.

[items.fn.const]

## Const functions

See const functions for the definition of const functions.

[items.fn.async]

## Async functions

[items.fn.async.intro]

Functions may be qualified as async, and this can also be combined with the `unsafe` qualifier:

    #![allow(unused)]
    fn main() {
    async fn regular_example() { }
    async unsafe fn unsafe_example() { }
    }

[items.fn.async.future]

Async functions do no work when called: instead, they capture their arguments into a future. When polled, that future will execute the function’s body.

[items.fn.async.desugar-brief]

An async function is roughly equivalent to a function that returns `impl Future` and with an `async move` block as its body:

    #![allow(unused)]
    fn main() {
    // Source
    async fn example(x: &str) -> usize {
        x.len()
    }
    }

is roughly equivalent to:

    #![allow(unused)]
    fn main() {
    use std::future::Future;
    // Desugared
    fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
        async move { x.len() }
    }
    }

[items.fn.async.desugar]

The actual desugaring is more complex:

[items.fn.async.lifetime-capture]

- The return type in the desugaring is assumed to capture all lifetime parameters from the `async fn` declaration. This can be seen in the desugared example above, which explicitly outlives, and hence captures, `'a`.

[items.fn.async.param-capture]

- The `async move` block in the body captures all function parameters, including those that are unused or bound to a `_` pattern. This ensures that function parameters are dropped in the same order as they would be if the function were not async, except that the drop occurs when the returned future has been fully awaited.

For more information on the effect of async, see `async` blocks.

[items.fn.async.edition2018]

> 2018 Edition differences

> Async functions are only available beginning with Rust 2018.

[items.fn.async.safety]

### Combining `async` and `unsafe`

[items.fn.async.safety.intro]

It is legal to declare a function that is both async and unsafe. The resulting function is unsafe to call and (like any async function) returns a future. This future is just an ordinary future and thus an `unsafe` context is not required to “await” it:

    #![allow(unused)]
    fn main() {
    // Returns a future that, when awaited, dereferences `x`.
    //
    // Soundness condition: `x` must be safe to dereference until
    // the resulting future is complete.
    async unsafe fn unsafe_example(x: *const i32) -> i32 {
      *x
    }

    async fn safe_example() {
        // An `unsafe` block is required to invoke the function initially:
        let p = 22;
        let future = unsafe { unsafe_example(&p) };

        // But no `unsafe` block required here. This will
        // read the value of `p`:
        let q = future.await;
    }
    }

Note that this behavior is a consequence of the desugaring to a function that returns an `impl Future` – in this case, the function we desugar to is an `unsafe` function, but the return value remains the same.

Unsafe is used on an async function in precisely the same way that it is used on other functions: it indicates that the function imposes some additional obligations on its caller to ensure soundness. As in any other unsafe function, these conditions may extend beyond the initial call itself – in the snippet above, for example, the `unsafe_example` function took a pointer `x` as argument, and then (when awaited) dereferenced that pointer. This implies that `x` would have to be valid until the future is finished executing, and it is the caller’s responsibility to ensure that.

[items.fn.attributes]

## Attributes on functions

[items.fn.attributes.intro]

Outer attributes are allowed on functions. Inner attributes are allowed directly after the `{` inside its body block.

This example shows an inner attribute on a function. The function is documented with just the word “Example”.

    #![allow(unused)]
    fn main() {
    fn documented() {
        #![doc = "Example"]
    }
    }

> Note

> Except for lints, it is idiomatic to only use outer attributes on function items.

[items.fn.attributes.builtin-attributes]

The attributes that have meaning on a function are:

- `cfg_attr`
- `cfg`
- `cold`
- `deprecated`
- `doc`
- `export_name`
- `inline`
- `link_section`
- `must_use`
- `no_mangle`
- Lint check attributes
- Procedural macro attributes
- Testing attributes

[items.fn.param-attributes]

## Attributes on function parameters

[items.fn.param-attributes.intro]

Outer attributes are allowed on function parameters and the permitted built-in attributes are restricted to `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, and `forbid`.

    #![allow(unused)]
    fn main() {
    fn len(
        #[cfg(windows)] slice: &[u16],
        #[cfg(not(windows))] slice: &[u8],
    ) -> usize {
        slice.len()
    }
    }

[items.fn.param-attributes.parsed-attributes]

Inert helper attributes used by procedural macro attributes applied to items are also allowed but be careful to not include these inert attributes in your final `TokenStream`.

For example, the following code defines an inert `some_inert_attribute` attribute that is not formally defined anywhere and the `some_proc_macro_attribute` procedural macro is responsible for detecting its presence and removing it from the output token stream.

    #[some_proc_macro_attribute]
    fn foo_oof(#[some_inert_attribute] arg: u8) {
    }

1. The `async` qualifier is not allowed in the 2015 edition. ↩

2. Relevant to editions earlier than Rust 2024: Within `extern` blocks, the `safe` or `unsafe` function qualifier is only allowed when the `extern` is qualified as `unsafe`. ↩

3. The `safe` function qualifier is only allowed semantically within `extern` blocks. ↩

4. Function parameters with only a type are only allowed in an associated function of a trait item in the 2015 edition. ↩

[items.type]

# Type aliases

[items.type.syntax]

Syntax
TypeAlias →
type IDENTIFIER GenericParams? ( : TypeParamBounds )?
WhereClause?
( = Type WhereClause? )? ;

[items.type.intro]

A type alias defines a new name for an existing type in the type namespace of the module or block where it is located. Type aliases are declared with the keyword `type`. Every value has a single, specific type, but may implement several different traits, and may be compatible with several different type constraints.

For example, the following defines the type `Point` as a synonym for the type `(u8, u8)`, the type of pairs of unsigned 8 bit integers:

    #![allow(unused)]
    fn main() {
    type Point = (u8, u8);
    let p: Point = (41, 68);
    }

[items.type.constructor-alias]

A type alias to a tuple-struct or unit-struct cannot be used to qualify that type’s constructor:

    #![allow(unused)]
    fn main() {
    struct MyStruct(u32);

    use MyStruct as UseAlias;
    type TypeAlias = MyStruct;

    let _ = UseAlias(5); // OK
    let _ = TypeAlias(5); // Doesn't work
    }

[items.type.associated-type]

A type alias, when not used as an associated type, must include a Type and may not include TypeParamBounds.

[items.type.associated-trait]

A type alias, when used as an associated type in a trait, must not include a Type specification but may include TypeParamBounds.

[items.type.associated-impl]

A type alias, when used as an associated type in a trait impl, must include a Type specification and may not include TypeParamBounds.

[items.type.deprecated]

Where clauses before the equals sign on a type alias in a trait impl (like `type TypeAlias<T> where T: Foo = Bar<T>`) are deprecated. Where clauses after the equals sign (like `type TypeAlias<T> = Bar<T> where T: Foo`) are preferred.

[items.struct]

# Structs

[items.struct.syntax]

Syntax
Struct →
StructStruct
| TupleStruct

StructStruct →
struct IDENTIFIER GenericParams? WhereClause? ( { StructFields? } | ; )

TupleStruct →
struct IDENTIFIER GenericParams? ( TupleFields? ) WhereClause? ;

StructFields → StructField ( , StructField )* ,?

StructField → OuterAttribute* Visibility? IDENTIFIER : Type

TupleFields → TupleField ( , TupleField )* ,?

TupleField → OuterAttribute* Visibility? Type

[items.struct.intro]

A struct is a nominal struct type defined with the keyword `struct`.

[items.struct.namespace]

A struct declaration defines the given name in the type namespace of the module or block where it is located.

An example of a `struct` item and its use:

    #![allow(unused)]
    fn main() {
    struct Point {x: i32, y: i32}
    let p = Point {x: 10, y: 11};
    let px: i32 = p.x;
    }

[items.struct.tuple]

A tuple struct is a nominal tuple type, and is also defined with the keyword `struct`. In addition to defining a type, it also defines a constructor of the same name in the value namespace. The constructor is a function which can be called to create a new instance of the struct. For example:

    #![allow(unused)]
    fn main() {
    struct Point(i32, i32);
    let p = Point(10, 11);
    let px: i32 = match p { Point(x, _) => x };
    }

[items.struct.unit]

A unit-like struct is a struct without any fields, defined by leaving off the list of fields entirely. Such a struct implicitly defines a constant of its type with the same name. For example:

    #![allow(unused)]
    fn main() {
    struct Cookie;
    let c = [Cookie, Cookie {}, Cookie, Cookie {}];
    }

is equivalent to

    #![allow(unused)]
    fn main() {
    struct Cookie {}
    const Cookie: Cookie = Cookie {};
    let c = [Cookie, Cookie {}, Cookie, Cookie {}];
    }

[items.struct.layout]

The precise memory layout of a struct is not specified. One can specify a particular layout using the `repr` attribute.

[items.enum]

# Enumerations

[items.enum.syntax]

Syntax
Enumeration →
enum IDENTIFIER GenericParams? WhereClause? { EnumVariants? }

EnumVariants → EnumVariant ( , EnumVariant )* ,?

EnumVariant →
OuterAttribute* Visibility?
IDENTIFIER ( EnumVariantTuple | EnumVariantStruct )? EnumVariantDiscriminant?

EnumVariantTuple → ( TupleFields? )

EnumVariantStruct → { StructFields? }

EnumVariantDiscriminant → = Expression

[items.enum.intro]

An enumeration, also referred to as an enum, is a simultaneous definition of a nominal enumerated type as well as a set of constructors, that can be used to create or pattern-match values of the corresponding enumerated type.

[items.enum.decl]

Enumerations are declared with the keyword `enum`.

[items.enum.namespace]

The `enum` declaration defines the enumeration type in the type namespace of the module or block where it is located.

An example of an `enum` item and its use:

    #![allow(unused)]
    fn main() {
    enum Animal {
        Dog,
        Cat,
    }

    let mut a: Animal = Animal::Dog;
    a = Animal::Cat;
    }

[items.enum.constructor]

Enum constructors can have either named or unnamed fields:

    #![allow(unused)]
    fn main() {
    enum Animal {
        Dog(String, f64),
        Cat { name: String, weight: f64 },
    }

    let mut a: Animal = Animal::Dog("Cocoa".to_string(), 37.2);
    a = Animal::Cat { name: "Spotty".to_string(), weight: 2.7 };
    }

In this example, `Cat` is a struct-like enum variant, whereas `Dog` is simply called an enum variant.

[items.enum.fieldless]

An enum where no constructors contain fields is called a field-less enum. For example, this is a fieldless enum:

    #![allow(unused)]
    fn main() {
    enum Fieldless {
        Tuple(),
        Struct{},
        Unit,
    }
    }

[items.enum.unit-only]

If a field-less enum only contains unit variants, the enum is called an unit-only enum. For example:

    #![allow(unused)]
    fn main() {
    enum Enum {
        Foo = 3,
        Bar = 2,
        Baz = 1,
    }
    }

[items.enum.constructor-names]

Variant constructors are similar to struct definitions, and can be referenced by a path from the enumeration name, including in use declarations.

[items.enum.constructor-namespace]

Each variant defines its type in the type namespace, though that type cannot be used as a type specifier. Tuple-like and unit-like variants also define a constructor in the value namespace.

[items.enum.struct-expr]

A struct-like variant can be instantiated with a struct expression.

[items.enum.tuple-expr]

A tuple-like variant can be instantiated with a call expression or a struct expression.

[items.enum.path-expr]

A unit-like variant can be instantiated with a path expression or a struct expression. For example:

    #![allow(unused)]
    fn main() {
    enum Examples {
        UnitLike,
        TupleLike(i32),
        StructLike { value: i32 },
    }

    use Examples::*; // Creates aliases to all variants.
    let x = UnitLike; // Path expression of the const item.
    let x = UnitLike {}; // Struct expression.
    let y = TupleLike(123); // Call expression.
    let y = TupleLike { 0: 123 }; // Struct expression using integer field names.
    let z = StructLike { value: 123 }; // Struct expression.
    }

[items.enum.discriminant]

## Discriminants

[items.enum.discriminant.intro]

Each enum instance has a discriminant: an integer logically associated to it that is used to determine which variant it holds.

[items.enum.discriminant.repr-rust]

Under the `Rust` representation, the discriminant is interpreted as an `isize` value. However, the compiler is allowed to use a smaller type (or another means of distinguishing variants) in its actual memory layout.

### Assigning discriminant values

[items.enum.discriminant.explicit]

#### Explicit discriminants

[items.enum.discriminant.explicit.intro]

In two circumstances, the discriminant of a variant may be explicitly set by following the variant name with `=` and a constant expression:

[items.enum.discriminant.explicit.unit-only]

1. if the enumeration is “unit-only”.

[items.enum.discriminant.explicit.primitive-repr]

2. if a primitive representation is used. For example:

       #![allow(unused)]
       fn main() {
       #[repr(u8)]
       enum Enum {
           Unit = 3,
           Tuple(u16),
           Struct {
               a: u8,
               b: u16,
           } = 1,
       }
       }

[items.enum.discriminant.implicit]

#### Implicit discriminants

If a discriminant for a variant is not specified, then it is set to one higher than the discriminant of the previous variant in the declaration. If the discriminant of the first variant in the declaration is unspecified, then it is set to zero.

    #![allow(unused)]
    fn main() {
    enum Foo {
        Bar,            // 0
        Baz = 123,      // 123
        Quux,           // 124
    }

    let baz_discriminant = Foo::Baz as u32;
    assert_eq!(baz_discriminant, 123);
    }

[items.enum.discriminant.restrictions]

#### Restrictions

[items.enum.discriminant.restrictions.same-discriminant]

It is an error when two variants share the same discriminant.

    #![allow(unused)]
    fn main() {
    enum SharedDiscriminantError {
        SharedA = 1,
        SharedB = 1
    }

    enum SharedDiscriminantError2 {
        Zero,       // 0
        One,        // 1
        OneToo = 1  // 1 (collision with previous!)
    }
    }

[items.enum.discriminant.restrictions.above-max-discriminant]

It is also an error to have an unspecified discriminant where the previous discriminant is the maximum value for the size of the discriminant.

    #![allow(unused)]
    fn main() {
    #[repr(u8)]
    enum OverflowingDiscriminantError {
        Max = 255,
        MaxPlusOne // Would be 256, but that overflows the enum.
    }

    #[repr(u8)]
    enum OverflowingDiscriminantError2 {
        MaxMinusOne = 254, // 254
        Max,               // 255
        MaxPlusOne         // Would be 256, but that overflows the enum.
    }
    }

### Accessing discriminant

#### Via `mem::discriminant`

[items.enum.discriminant.access-opaque]

`std::mem::discriminant` returns an opaque reference to the discriminant of an enum value which can be compared. This cannot be used to get the value of the discriminant.

[items.enum.discriminant.coercion]

#### Casting

[items.enum.discriminant.coercion.intro]

If an enumeration is unit-only (with no tuple and struct variants), then its discriminant can be directly accessed with a numeric cast; e.g.:

    #![allow(unused)]
    fn main() {
    enum Enum {
        Foo,
        Bar,
        Baz,
    }

    assert_eq!(0, Enum::Foo as isize);
    assert_eq!(1, Enum::Bar as isize);
    assert_eq!(2, Enum::Baz as isize);
    }

[items.enum.discriminant.coercion.fieldless]

Field-less enums can be cast if they do not have explicit discriminants, or where only unit variants are explicit.

    #![allow(unused)]
    fn main() {
    enum Fieldless {
        Tuple(),
        Struct{},
        Unit,
    }

    assert_eq!(0, Fieldless::Tuple() as isize);
    assert_eq!(1, Fieldless::Struct{} as isize);
    assert_eq!(2, Fieldless::Unit as isize);

    #[repr(u8)]
    enum FieldlessWithDiscriminants {
        First = 10,
        Tuple(),
        Second = 20,
        Struct{},
        Unit,
    }

    assert_eq!(10, FieldlessWithDiscriminants::First as u8);
    assert_eq!(11, FieldlessWithDiscriminants::Tuple() as u8);
    assert_eq!(20, FieldlessWithDiscriminants::Second as u8);
    assert_eq!(21, FieldlessWithDiscriminants::Struct{} as u8);
    assert_eq!(22, FieldlessWithDiscriminants::Unit as u8);
    }

#### Pointer casting

[items.enum.discriminant.access-memory]

If the enumeration specifies a primitive representation, then the discriminant may be reliably accessed via unsafe pointer casting:

    #![allow(unused)]
    fn main() {
    #[repr(u8)]
    enum Enum {
        Unit,
        Tuple(bool),
        Struct{a: bool},
    }

    impl Enum {
        fn discriminant(&self) -> u8 {
            unsafe { *(self as *const Self as *const u8) }
        }
    }

    let unit_like = Enum::Unit;
    let tuple_like = Enum::Tuple(true);
    let struct_like = Enum::Struct{a: false};

    assert_eq!(0, unit_like.discriminant());
    assert_eq!(1, tuple_like.discriminant());
    assert_eq!(2, struct_like.discriminant());
    }

[items.enum.empty]

## Zero-variant enums

[items.enum.empty.intro]

Enums with zero variants are known as zero-variant enums. As they have no valid values, they cannot be instantiated.

    #![allow(unused)]
    fn main() {
    enum ZeroVariants {}
    }

[items.enum.empty.uninhabited]

Zero-variant enums are equivalent to the never type, but they cannot be coerced into other types.

    #![allow(unused)]
    fn main() {
    enum ZeroVariants {}
    let x: ZeroVariants = panic!();
    let y: u32 = x; // mismatched type error
    }

[items.enum.variant-visibility]

## Variant visibility

Enum variants syntactically allow a Visibility annotation, but this is rejected when the enum is validated. This allows items to be parsed with a unified syntax across different contexts where they are used.

    #![allow(unused)]
    fn main() {
    macro_rules! mac_variant {
        ($vis:vis $name:ident) => {
            enum $name {
                $vis Unit,

                $vis Tuple(u8, u16),

                $vis Struct { f: u8 },
            }
        }
    }

    // Empty `vis` is allowed.
    mac_variant! { E }

    // This is allowed, since it is removed before being validated.
    #[cfg(false)]
    enum E {
        pub U,
        pub(crate) T(u8),
        pub(super) T { f: String }
    }
    }

[items.union]

# Unions

[items.union.syntax]

Syntax
Union →
union IDENTIFIER GenericParams? WhereClause? { StructFields? }

[items.union.intro]

A union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`.

[items.union.namespace]

A union declaration defines the given name in the type namespace of the module or block where it is located.

    #![allow(unused)]
    fn main() {
    #[repr(C)]
    union MyUnion {
        f1: u32,
        f2: f32,
    }
    }

[items.union.common-storage]

The key property of unions is that all fields of a union share common storage. As a result, writes to one field of a union can overwrite its other fields, and size of a union is determined by the size of its largest field.

[items.union.field-restrictions]

Union field types are restricted to the following subset of types:

[items.union.field-copy]

- `Copy` types

[items.union.field-references]

- References (`&T` and `&mut T` for arbitrary `T`)

[items.union.field-manually-drop]

- `ManuallyDrop<T>` (for arbitrary `T`)

[items.union.field-tuple]

- Tuples and arrays containing only allowed union field types

[items.union.drop]

This restriction ensures, in particular, that union fields never need to be dropped. Like for structs and enums, it is possible to `impl Drop` for a union to manually define what happens when it gets dropped.

[items.union.fieldless]

Unions without any fields are not accepted by the compiler, but can be accepted by macros.

[items.union.init]

## Initialization of a union

[items.union.init.intro]

A value of a union type can be created using the same syntax that is used for struct types, except that it must specify exactly one field:

    #![allow(unused)]
    fn main() {
    union MyUnion { f1: u32, f2: f32 }

    let u = MyUnion { f1: 1 };
    }

[items.union.init.result]

The expression above creates a value of type `MyUnion` and initializes the storage using field `f1`. The union can be accessed using the same syntax as struct fields:

    #![allow(unused)]
    fn main() {
    union MyUnion { f1: u32, f2: f32 }

    let u = MyUnion { f1: 1 };
    let f = unsafe { u.f1 };
    }

[items.union.fields]

## Reading and writing union fields

[items.union.fields.intro]

Unions have no notion of an “active field”. Instead, every union access just interprets the storage as the type of the field used for the access.

[items.union.fields.read]

Reading a union field reads the bits of the union at the field’s type.

[items.union.fields.offset]

Fields might have a non-zero offset (except when the C representation is used); in that case the bits starting at the offset of the fields are read

[items.union.fields.validity]

It is the programmer’s responsibility to make sure that the data is valid at the field’s type. Failing to do so results in undefined behavior. For example, reading the value `3` from a field of the boolean type is undefined behavior. Effectively, writing to and then reading from a union with the C representation is analogous to a `transmute` from the type used for writing to the type used for reading.

[items.union.fields.read-safety]

Consequently, all reads of union fields have to be placed in `unsafe` blocks:

    #![allow(unused)]
    fn main() {
    union MyUnion { f1: u32, f2: f32 }
    let u = MyUnion { f1: 1 };

    unsafe {
        let f = u.f1;
    }
    }

Commonly, code using unions will provide safe wrappers around unsafe union field accesses.

[items.union.fields.write-safety]

In contrast, writes to union fields are safe, since they just overwrite arbitrary data, but cannot cause undefined behavior. (Note that union field types can never have drop glue, so a union field write will never implicitly drop anything.)

[items.union.pattern]

## Pattern matching on unions

[items.union.pattern.intro]

Another way to access union fields is to use pattern matching.

[items.union.pattern.one-field]

Pattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field.

[items.union.pattern.safety]

Since pattern matching is like reading the union with a particular field, it has to be placed in `unsafe` blocks as well.

    #![allow(unused)]
    fn main() {
    union MyUnion { f1: u32, f2: f32 }

    fn f(u: MyUnion) {
        unsafe {
            match u {
                MyUnion { f1: 10 } => { println!("ten"); }
                MyUnion { f2 } => { println!("{}", f2); }
            }
        }
    }
    }

[items.union.pattern.subpattern]

Pattern matching may match a union as a field of a larger structure. In particular, when using a Rust union to implement a C tagged union via FFI, this allows matching on the tag and the corresponding field simultaneously:

    #![allow(unused)]
    fn main() {
    #[repr(u32)]
    enum Tag { I, F }

    #[repr(C)]
    union U {
        i: i32,
        f: f32,
    }

    #[repr(C)]
    struct Value {
        tag: Tag,
        u: U,
    }

    fn is_zero(v: Value) -> bool {
        unsafe {
            match v {
                Value { tag: Tag::I, u: U { i: 0 } } => true,
                Value { tag: Tag::F, u: U { f: num } } if num == 0.0 => true,
                _ => false,
            }
        }
    }
    }

[items.union.ref]

## References to union fields

[items.union.ref.intro]

Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields.

[items.union.ref.borrow]

Borrow checking rules have to be adjusted to account for this fact. As a result, if one field of a union is borrowed, all its remaining fields are borrowed as well for the same lifetime.

    #![allow(unused)]
    fn main() {
    union MyUnion { f1: u32, f2: f32 }
    // ERROR: cannot borrow `u` (via `u.f2`) as mutable more than once at a time
    fn test() {
        let mut u = MyUnion { f1: 1 };
        unsafe {
            let b1 = &mut u.f1;
    //                    ---- first mutable borrow occurs here (via `u.f1`)
            let b2 = &mut u.f2;
    //                    ^^^^ second mutable borrow occurs here (via `u.f2`)
            *b1 = 5;
        }
    //  - first borrow ends here
        assert_eq!(unsafe { u.f1 }, 5);
    }
    }

[items.union.ref.usage]

As you could see, in many aspects (except for layouts, safety, and ownership) unions behave exactly like structs, largely as a consequence of inheriting their syntactic shape from structs. This is also true for many unmentioned aspects of Rust language (such as privacy, name resolution, type inference, generics, trait implementations, inherent implementations, coherence, pattern checking, etc etc etc).

[items.const]

# Constant items

[items.const.syntax]

Syntax
ConstantItem →
const ( IDENTIFIER | _ ) : Type ( = Expression )? ;

[items.const.intro]

A constant item is an optionally named constant value which is not associated with a specific memory location in the program.

[items.const.behavior]

Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes usage of constants from external crates, and non-`Copy` types. References to the same constant are not necessarily guaranteed to refer to the same memory address.

[items.const.namespace]

The constant declaration defines the constant value in the value namespace of the module or block where it is located.

[items.const.static]

Constants must be explicitly typed. The type must have a `'static` lifetime: any references in the initializer must have `'static` lifetimes. References in the type of a constant default to `'static` lifetime; see static lifetime elision.

[items.const.static-temporary]

A reference to a constant will have `'static` lifetime if the constant value is eligible for promotion; otherwise, a temporary will be created.

    #![allow(unused)]
    fn main() {
    const BIT1: u32 = 1 << 0;
    const BIT2: u32 = 1 << 1;

    const BITS: [u32; 2] = [BIT1, BIT2];
    const STRING: &'static str = "bitstring";

    struct BitsNStrings<'a> {
        mybits: [u32; 2],
        mystring: &'a str,
    }

    const BITS_N_STRINGS: BitsNStrings<'static> = BitsNStrings {
        mybits: BITS,
        mystring: STRING,
    };
    }

[items.const.expr-omission]

The constant expression may only be omitted in a trait definition.

[items.const.destructor]

## Constants with destructors

Constants can contain destructors. Destructors are run when the value goes out of scope.

    #![allow(unused)]
    fn main() {
    struct TypeWithDestructor(i32);

    impl Drop for TypeWithDestructor {
        fn drop(&mut self) {
            println!("Dropped. Held {}.", self.0);
        }
    }

    const ZERO_WITH_DESTRUCTOR: TypeWithDestructor = TypeWithDestructor(0);

    fn create_and_drop_zero_with_destructor() {
        let x = ZERO_WITH_DESTRUCTOR;
        // x gets dropped at end of function, calling drop.
        // prints "Dropped. Held 0.".
    }
    }

[items.const.unnamed]

## Unnamed constant

[items.const.unnamed.intro]

Unlike an associated constant, a free constant may be unnamed by using an underscore instead of the name. For example:

    #![allow(unused)]
    fn main() {
    const _: () =  { struct _SameNameTwice; };

    // OK although it is the same name as above:
    const _: () =  { struct _SameNameTwice; };
    }

[items.const.unnamed.repetition]

As with underscore imports, macros may safely emit the same unnamed constant in the same scope more than once. For example, the following should not produce an error:

    #![allow(unused)]
    fn main() {
    macro_rules! m {
        ($item: item) => { $item $item }
    }

    m!(const _: () = (););
    // This expands to:
    // const _: () = ();
    // const _: () = ();
    }

[items.const.eval]

## Evaluation

Free constants are always evaluated at compile-time to surface panics. This happens even within an unused function:

    #![allow(unused)]
    fn main() {
    // Compile-time panic
    const PANIC: () = std::unimplemented!();

    fn unused_generic_function<T>() {
        // A failing compile-time assertion
        const _: () = assert!(usize::BITS == 0);
    }
    }

[items.static]

# Static items

[items.static.syntax]

Syntax
StaticItem →
ItemSafety?​1 static mut? IDENTIFIER : Type ( = Expression )? ;

[items.static.intro]

A static item is similar to a constant, except that it represents an allocation in the program that is initialized with the initializer expression. All references and raw pointers to the static refer to the same allocation.

[items.static.lifetime]

Static items have the `static` lifetime, which outlives all other lifetimes in a Rust program. Static items do not call `drop` at the end of the program.

[items.static.storage-disjointness]

If the `static` has a size of at least 1 byte, this allocation is disjoint from all other such `static` allocations as well as heap allocations and stack-allocated variables. However, the storage of immutable `static` items can overlap with allocations that do not themselves have a unique address, such as promoteds and `const` items.

[items.static.namespace]

The static declaration defines a static value in the value namespace of the module or block where it is located.

[items.static.init]

The static initializer is a constant expression evaluated at compile time. Static initializers may refer to and read from other statics. When reading from mutable statics, they read the initial value of that static.

[items.static.read-only]

Non-`mut` static items that contain a type that is not interior mutable may be placed in read-only memory.

[items.static.safety]

All access to a static is safe, but there are a number of restrictions on statics:

[items.static.sync]

- The type must have the `Sync` trait bound to allow thread-safe access.

[items.static.init.omission]

The initializer expression must be omitted in an external block, and must be provided for free static items.

[items.static.safety-qualifiers]

The `safe` and `unsafe` qualifiers are semantically only allowed when used in an external block.

[items.static.generics]

## Statics & generics

A static item defined in a generic scope (for example in a blanket or default implementation) will result in exactly one static item being defined, as if the static definition was pulled out of the current scope into the module. There will not be one item per monomorphization.

This code:

    use std::sync::atomic::{AtomicUsize, Ordering};

    trait Tr {
        fn default_impl() {
            static COUNTER: AtomicUsize = AtomicUsize::new(0);
            println!("default_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
        }

        fn blanket_impl();
    }

    struct Ty1 {}
    struct Ty2 {}

    impl<T> Tr for T {
        fn blanket_impl() {
            static COUNTER: AtomicUsize = AtomicUsize::new(0);
            println!("blanket_impl: counter was {}", COUNTER.fetch_add(1, Ordering::Relaxed));
        }
    }

    fn main() {
        <Ty1 as Tr>::default_impl();
        <Ty2 as Tr>::default_impl();
        <Ty1 as Tr>::blanket_impl();
        <Ty2 as Tr>::blanket_impl();
    }

prints

    default_impl: counter was 0
    default_impl: counter was 1
    blanket_impl: counter was 0
    blanket_impl: counter was 1

[items.static.mut]

## Mutable statics

[items.static.mut.intro]

If a static item is declared with the `mut` keyword, then it is allowed to be modified by the program. One of Rust’s goals is to make concurrency bugs hard to run into, and this is obviously a very large source of race conditions or other bugs.

[items.static.mut.safety]

For this reason, an `unsafe` block is required when either reading or writing a mutable static variable. Care should be taken to ensure that modifications to a mutable static are safe with respect to other threads running in the same process.

[items.static.mut.extern]

Mutable statics are still very useful, however. They can be used with C libraries and can also be bound from C libraries in an `extern` block.

    #![allow(unused)]
    fn main() {
    fn atomic_add(_: *mut u32, _: u32) -> u32 { 2 }

    static mut LEVELS: u32 = 0;

    // This violates the idea of no shared state, and this doesn't internally
    // protect against races, so this function is `unsafe`
    unsafe fn bump_levels_unsafe() -> u32 {
        unsafe {
            let ret = LEVELS;
            LEVELS += 1;
            return ret;
        }
    }

    // As an alternative to `bump_levels_unsafe`, this function is safe, assuming
    // that we have an atomic_add function which returns the old value. This
    // function is safe only if no other code accesses the static in a non-atomic
    // fashion. If such accesses are possible (such as in `bump_levels_unsafe`),
    // then this would need to be `unsafe` to indicate to the caller that they
    // must still guard against concurrent access.
    fn bump_levels_safe() -> u32 {
        unsafe {
            return atomic_add(&raw mut LEVELS, 1);
        }
    }
    }

[items.static.mut.sync]

Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the `Sync` trait.

[items.static.alternate]

## Using statics or consts

It can be confusing whether or not you should use a constant item or a static item. Constants should, in general, be preferred over statics unless one of the following are true:

- Large amounts of data are being stored.
- The single-address property of statics is required.
- Interior mutability is required.

1. The `safe` and `unsafe` function qualifiers are only allowed semantically within `extern` blocks. ↩

[items.traits]

# Traits

[items.traits.syntax]

Syntax
Trait →
unsafe? trait IDENTIFIER GenericParams? ( : TypeParamBounds? )? WhereClause?
{
InnerAttribute*
AssociatedItem*
}

[items.traits.intro]

A trait describes an abstract interface that types can implement. This interface consists of associated items, which come in three varieties:

- functions
- types
- constants

[items.traits.namespace]

The trait declaration defines a trait in the type namespace of the module or block where it is located.

[items.traits.associated-item-namespaces]

Associated items are defined as members of the trait within their respective namespaces. Associated types are defined in the type namespace. Associated constants and associated functions are defined in the value namespace.

[items.traits.self-param]

All traits define an implicit type parameter `Self` that refers to “the type that is implementing this interface”. Traits may also contain additional type parameters. These type parameters, including `Self`, may be constrained by other traits and so forth as usual.

[items.traits.impls]

Traits are implemented for specific types through separate implementations.

[items.traits.associated-item-decls]

Trait functions may omit the function body by replacing it with a semicolon. This indicates that the implementation must define the function. If the trait function defines a body, this definition acts as a default for any implementation which does not override it. Similarly, associated constants may omit the equals sign and expression to indicate implementations must define the constant value. Associated types must never define the type, the type may only be specified in an implementation.

    #![allow(unused)]
    fn main() {
    // Examples of associated trait items with and without definitions.
    trait Example {
        const CONST_NO_DEFAULT: i32;
        const CONST_WITH_DEFAULT: i32 = 99;
        type TypeNoDefault;
        fn method_without_default(&self);
        fn method_with_default(&self) {}
    }
    }

[items.traits.const-fn]

Trait functions are not allowed to be `const`.

[items.traits.bounds]

## Trait bounds

Generic items may use traits as bounds on their type parameters.

[items.traits.generic]

## Generic traits

Type parameters can be specified for a trait to make it generic. These appear after the trait name, using the same syntax used in generic functions.

    #![allow(unused)]
    fn main() {
    trait Seq<T> {
        fn len(&self) -> u32;
        fn elt_at(&self, n: u32) -> T;
        fn iter<F>(&self, f: F) where F: Fn(T);
    }
    }

[items.traits.dyn-compatible]

## Dyn compatibility

[items.traits.dyn-compatible.intro]

A dyn-compatible trait can be the base trait of a trait object. A trait is dyn compatible if it has the following qualities:

[items.traits.dyn-compatible.supertraits]

- All supertraits must also be dyn compatible.

[items.traits.dyn-compatible.sized]

- `Sized` must not be a supertrait. In other words, it must not require `Self: Sized`.

[items.traits.dyn-compatible.associated-consts]

- It must not have any associated constants.

[items.traits.dyn-compatible.associated-types]

- It must not have any associated types with generics.

[items.traits.dyn-compatible.associated-functions]

- All associated functions must either be dispatchable from a trait object or be explicitly non-dispatchable:
  - Dispatchable functions must:
    - Not have any type parameters (although lifetime parameters are allowed).
    - Be a method that does not use `Self` except in the type of the receiver.
    - Have a receiver with one of the following types:
      - `&Self` (i.e. `&self`)
      - `&mut Self` (i.e `&mut self`)
      - `Box<Self>`
      - `Rc<Self>`
      - `Arc<Self>`
      - `Pin<P>` where `P` is one of the types above
    - Not have an opaque return type; that is,
      - Not be an `async fn` (which has a hidden `Future` type).
      - Not have a return position `impl Trait` type (`fn example(&self) -> impl Trait`).
    - Not have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).
  - Explicitly non-dispatchable functions require:
    - Have a `where Self: Sized` bound (receiver type of `Self` (i.e. `self`) implies this).

[items.traits.dyn-compatible.async-traits]

- The `AsyncFn`, `AsyncFnMut`, and `AsyncFnOnce` traits are not dyn-compatible.

> Note

> This concept was formerly known as object safety.

    #![allow(unused)]
    fn main() {
    use std::rc::Rc;
    use std::sync::Arc;
    use std::pin::Pin;
    // Examples of dyn compatible methods.
    trait TraitMethods {
        fn by_ref(self: &Self) {}
        fn by_ref_mut(self: &mut Self) {}
        fn by_box(self: Box<Self>) {}
        fn by_rc(self: Rc<Self>) {}
        fn by_arc(self: Arc<Self>) {}
        fn by_pin(self: Pin<&Self>) {}
        fn with_lifetime<'a>(self: &'a Self) {}
        fn nested_pin(self: Pin<Arc<Self>>) {}
    }
    struct S;
    impl TraitMethods for S {}
    let t: Box<dyn TraitMethods> = Box::new(S);
    }

    #![allow(unused)]
    fn main() {
    // This trait is dyn compatible, but these methods cannot be dispatched on a trait object.
    trait NonDispatchable {
        // Non-methods cannot be dispatched.
        fn foo() where Self: Sized {}
        // Self type isn't known until runtime.
        fn returns(&self) -> Self where Self: Sized;
        // `other` may be a different concrete type of the receiver.
        fn param(&self, other: Self) where Self: Sized {}
        // Generics are not compatible with vtables.
        fn typed<T>(&self, x: T) where Self: Sized {}
    }

    struct S;
    impl NonDispatchable for S {
        fn returns(&self) -> Self where Self: Sized { S }
    }
    let obj: Box<dyn NonDispatchable> = Box::new(S);
    obj.returns(); // ERROR: cannot call with Self return
    obj.param(S);  // ERROR: cannot call with Self parameter
    obj.typed(1);  // ERROR: cannot call with generic type
    }

    #![allow(unused)]
    fn main() {
    use std::rc::Rc;
    // Examples of dyn-incompatible traits.
    trait DynIncompatible {
        const CONST: i32 = 1;  // ERROR: cannot have associated const

        fn foo() {}  // ERROR: associated function without Sized
        fn returns(&self) -> Self; // ERROR: Self in return type
        fn typed<T>(&self, x: T) {} // ERROR: has generic type parameters
        fn nested(self: Rc<Box<Self>>) {} // ERROR: nested receiver cannot be dispatched on
    }

    struct S;
    impl DynIncompatible for S {
        fn returns(&self) -> Self { S }
    }
    let obj: Box<dyn DynIncompatible> = Box::new(S); // ERROR
    }

    #![allow(unused)]
    fn main() {
    // `Self: Sized` traits are dyn-incompatible.
    trait TraitWithSize where Self: Sized {}

    struct S;
    impl TraitWithSize for S {}
    let obj: Box<dyn TraitWithSize> = Box::new(S); // ERROR
    }

    #![allow(unused)]
    fn main() {
    // Dyn-incompatible if `Self` is a type argument.
    trait Super<A> {}
    trait WithSelf: Super<Self> where Self: Sized {}

    struct S;
    impl<A> Super<A> for S {}
    impl WithSelf for S {}
    let obj: Box<dyn WithSelf> = Box::new(S); // ERROR: cannot use `Self` type parameter
    }

[items.traits.supertraits]

## Supertraits

[items.traits.supertraits.intro]

Supertraits are traits that are required to be implemented for a type to implement a specific trait. Furthermore, anywhere a generic or trait object is bounded by a trait, it has access to the associated items of its supertraits.

[items.traits.supertraits.decl]

Supertraits are declared by trait bounds on the `Self` type of a trait and transitively the supertraits of the traits declared in those trait bounds. It is an error for a trait to be its own supertrait.

[items.traits.supertraits.subtrait]

The trait with a supertrait is called a subtrait of its supertrait.

The following is an example of declaring `Shape` to be a supertrait of `Circle`.

    #![allow(unused)]
    fn main() {
    trait Shape { fn area(&self) -> f64; }
    trait Circle: Shape { fn radius(&self) -> f64; }
    }

And the following is the same example, except using where clauses.

    #![allow(unused)]
    fn main() {
    trait Shape { fn area(&self) -> f64; }
    trait Circle where Self: Shape { fn radius(&self) -> f64; }
    }

This next example gives `radius` a default implementation using the `area` function from `Shape`.

    #![allow(unused)]
    fn main() {
    trait Shape { fn area(&self) -> f64; }
    trait Circle where Self: Shape {
        fn radius(&self) -> f64 {
            // A = pi * r^2
            // so algebraically,
            // r = sqrt(A / pi)
            (self.area() / std::f64::consts::PI).sqrt()
        }
    }
    }

This next example calls a supertrait method on a generic parameter.

    #![allow(unused)]
    fn main() {
    trait Shape { fn area(&self) -> f64; }
    trait Circle: Shape { fn radius(&self) -> f64; }
    fn print_area_and_radius<C: Circle>(c: C) {
        // Here we call the area method from the supertrait `Shape` of `Circle`.
        println!("Area: {}", c.area());
        println!("Radius: {}", c.radius());
    }
    }

Similarly, here is an example of calling supertrait methods on trait objects.

    #![allow(unused)]
    fn main() {
    trait Shape { fn area(&self) -> f64; }
    trait Circle: Shape { fn radius(&self) -> f64; }
    struct UnitCircle;
    impl Shape for UnitCircle { fn area(&self) -> f64 { std::f64::consts::PI } }
    impl Circle for UnitCircle { fn radius(&self) -> f64 { 1.0 } }
    let circle = UnitCircle;
    let circle = Box::new(circle) as Box<dyn Circle>;
    let nonsense = circle.radius() * circle.area();
    }

[items.traits.safety]

## Unsafe traits

[items.traits.safety.intro]

Traits items that begin with the `unsafe` keyword indicate that implementing the trait may be unsafe. It is safe to use a correctly implemented unsafe trait. The trait implementation must also begin with the `unsafe` keyword.

`Sync` and `Send` are examples of unsafe traits.

[items.traits.params]

## Parameter patterns

[items.traits.params.patterns-no-body]

Parameters in associated functions without a body only allow IDENTIFIER or `_` wild card patterns, as well as the form allowed by SelfParam. `mut` IDENTIFIER is currently allowed, but it is deprecated and will become a hard error in the future.

    #![allow(unused)]
    fn main() {
    trait T {
        fn f1(&self);
        fn f2(x: Self, _: i32);
    }
    }

    #![allow(unused)]
    fn main() {
    trait T {
        fn f2(&x: &i32); // ERROR: patterns aren't allowed in functions without bodies
    }
    }

[items.traits.params.patterns-with-body]

Parameters in associated functions with a body only allow irrefutable patterns.

    #![allow(unused)]
    fn main() {
    trait T {
        fn f1((a, b): (i32, i32)) {} // OK: is irrefutable
    }
    }

    #![allow(unused)]
    fn main() {
    trait T {
        fn f1(123: i32) {} // ERROR: pattern is refutable
        fn f2(Some(x): Option<i32>) {} // ERROR: pattern is refutable
    }
    }

[items.traits.params.pattern-required.edition2018]

> 2018 Edition differences

> Prior to the 2018 edition, the pattern for an associated function parameter is optional:

>     #![allow(unused)]
>     fn main() {
>     // 2015 Edition
>     trait T {
>         fn f(i32); // OK: parameter identifiers are not required
>     }
>     }

> Beginning in the 2018 edition, patterns are no longer optional.

[items.traits.params.restriction-patterns.edition2018]

> 2018 Edition differences

> Prior to the 2018 edition, parameters in associated functions with a body are limited to the following kinds of patterns:

> - IDENTIFIER
> - `mut` IDENTIFIER
> - `_`
> - `&` IDENTIFIER
> - `&&` IDENTIFIER

>     #![allow(unused)]
>     fn main() {
>     // 2015 Edition
>     trait T {
>         fn f1((a, b): (i32, i32)) {} // ERROR: pattern not allowed
>     }
>     }

> Beginning in 2018, all irrefutable patterns are allowed as described in items.traits.params.patterns-with-body.

[items.traits.associated-visibility]

## Item visibility

[items.traits.associated-visibility.intro]

Trait items syntactically allow a Visibility annotation, but this is rejected when the trait is validated. This allows items to be parsed with a unified syntax across different contexts where they are used. As an example, an empty `vis` macro fragment specifier can be used for trait items, where the macro rule may be used in other situations where visibility is allowed.

    macro_rules! create_method {
        ($vis:vis $name:ident) => {
            $vis fn $name(&self) {}
        };
    }

    trait T1 {
        // Empty `vis` is allowed.
        create_method! { method_of_t1 }
    }

    struct S;

    impl S {
        // Visibility is allowed here.
        create_method! { pub method_of_s }
    }

    impl T1 for S {}

    fn main() {
        let s = S;
        s.method_of_t1();
        s.method_of_s();
    }

[items.impl]

# Implementations

[items.impl.syntax]

Syntax
Implementation → InherentImpl | TraitImpl

InherentImpl →
impl GenericParams? Type WhereClause? {
InnerAttribute*
AssociatedItem*
}

TraitImpl →
unsafe? impl GenericParams? !? TypePath for Type
WhereClause?
{
InnerAttribute*
AssociatedItem*
}

[items.impl.intro]

An implementation is an item that associates items with an implementing type. Implementations are defined with the keyword `impl` and contain functions that belong to an instance of the type that is being implemented or to the type statically.

[items.impl.kinds]

There are two types of implementations:

- inherent implementations
- trait implementations

[items.impl.inherent]

## Inherent implementations

[items.impl.inherent.intro]

An inherent implementation is defined as the sequence of the `impl` keyword, generic type declarations, a path to a nominal type, a where clause, and a bracketed set of associable items.

[items.impl.inherent.implementing-type]

The nominal type is called the implementing type and the associable items are the associated items to the implementing type.

[items.impl.inherent.associated-items]

Inherent implementations associate the contained items to the implementing type.

[items.impl.inherent.associated-items.allowed-items]

Inherent implementations can contain associated functions (including methods) and associated constants.

[items.impl.inherent.type-alias]

They cannot contain associated type aliases.

[items.impl.inherent.associated-item-path]

The path to an associated item is any path to the implementing type, followed by the associated item’s identifier as the final path component.

[items.impl.inherent.coherence]

A type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition.

    pub mod color {
        pub struct Color(pub u8, pub u8, pub u8);

        impl Color {
            pub const WHITE: Color = Color(255, 255, 255);
        }
    }

    mod values {
        use super::color::Color;
        impl Color {
            pub fn red() -> Color {
                Color(255, 0, 0)
            }
        }
    }

    pub use self::color::Color;
    fn main() {
        // Actual path to the implementing type and impl in the same module.
        color::Color::WHITE;

        // Impl blocks in different modules are still accessed through a path to the type.
        color::Color::red();

        // Re-exported paths to the implementing type also work.
        Color::red();

        // Does not work, because use in `values` is not pub.
        // values::Color::red();
    }

[items.impl.trait]

## Trait implementations

[items.impl.trait.intro]

A trait implementation is defined like an inherent implementation except that the optional generic type declarations are followed by a trait, followed by the keyword `for`, followed by a path to a nominal type.

[items.impl.trait.implemented-trait]

The trait is known as the implemented trait. The implementing type implements the implemented trait.

[items.impl.trait.def-requirement]

A trait implementation must define all non-default associated items declared by the implemented trait, may redefine default associated items defined by the implemented trait, and cannot define any other items.

[items.impl.trait.associated-item-path]

The path to the associated items is `<` followed by a path to the implementing type followed by `as` followed by a path to the trait followed by `>` as a path component followed by the associated item’s path component.

[items.impl.trait.safety]

Unsafe traits require the trait implementation to begin with the `unsafe` keyword.

    #![allow(unused)]
    fn main() {
    #[derive(Copy, Clone)]
    struct Point {x: f64, y: f64};
    type Surface = i32;
    struct BoundingBox {x: f64, y: f64, width: f64, height: f64};
    trait Shape { fn draw(&self, s: Surface); fn bounding_box(&self) -> BoundingBox; }
    fn do_draw_circle(s: Surface, c: Circle) { }
    struct Circle {
        radius: f64,
        center: Point,
    }

    impl Copy for Circle {}

    impl Clone for Circle {
        fn clone(&self) -> Circle { *self }
    }

    impl Shape for Circle {
        fn draw(&self, s: Surface) { do_draw_circle(s, *self); }
        fn bounding_box(&self) -> BoundingBox {
            let r = self.radius;
            BoundingBox {
                x: self.center.x - r,
                y: self.center.y - r,
                width: 2.0 * r,
                height: 2.0 * r,
            }
        }
    }
    }

[items.impl.trait.coherence]

### Trait implementation coherence

[items.impl.trait.coherence.intro]

A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances.

[items.impl.trait.coherence.overlapping]

Two trait implementations overlap when there is a non-empty intersection of the traits the implementation is for, the implementations can be instantiated with the same type.

[items.impl.trait.orphan-rule]

#### Orphan rules

[items.impl.trait.orphan-rule.intro]

The orphan rule states that a trait implementation is only allowed if either the trait or at least one of the types in the implementation is defined in the current crate. It prevents conflicting trait implementations across different crates and is key to ensuring coherence.

An orphan implementation is one that implements a foreign trait for a foreign type. If these were freely allowed, two crates could implement the same trait for the same type in incompatible ways, creating a situation where adding or updating a dependency could break compilation due to conflicting implementations.

The orphan rule enables library authors to add new implementations to their traits without fear that they’ll break downstream code. Without these restrictions, a library couldn’t add an implementation like `impl<T: Display> MyTrait for T` without potentially conflicting with downstream implementations.

[items.impl.trait.orphan-rule.general]

Given `impl<P1..=Pn> Trait<T1..=Tn> for T0`, an `impl` is valid only if at least one of the following is true:

- `Trait` is a local trait
- All of
  - At least one of the types `T0..=Tn` must be a local type. Let `Ti` be the first such type.
  - No uncovered type parameters `P1..=Pn` may appear in `T0..Ti` (excluding `Ti`)

[items.impl.trait.uncovered-param]

Only the appearance of uncovered type parameters is restricted.

[items.impl.trait.fundamental]

Note that for the purposes of coherence, fundamental types are special. The `T` in `Box<T>` is not considered covered, and `Box<LocalType>` is considered local.

[items.impl.generics]

## Generic implementations

[items.impl.generics.intro]

An implementation can take generic parameters, which can be used in the rest of the implementation. Implementation parameters are written directly after the `impl` keyword.

    #![allow(unused)]
    fn main() {
    trait Seq<T> { fn dummy(&self, _: T) { } }
    impl<T> Seq<T> for Vec<T> {
        /* ... */
    }
    impl Seq<bool> for u32 {
        /* Treat the integer as a sequence of bits */
    }
    }

[items.impl.generics.usage]

Generic parameters constrain an implementation if the parameter appears at least once in one of:

- The implemented trait, if it has one
- The implementing type
- As an associated type in the bounds of a type that contains another parameter that constrains the implementation

[items.impl.generics.constrain]

Type and const parameters must always constrain the implementation. Lifetimes must constrain the implementation if the lifetime is used in an associated type.

Examples of constraining situations:

    #![allow(unused)]
    fn main() {
    trait Trait{}
    trait GenericTrait<T> {}
    trait HasAssocType { type Ty; }
    struct Struct;
    struct GenericStruct<T>(T);
    struct ConstGenericStruct<const N: usize>([(); N]);
    // T constrains by being an argument to GenericTrait.
    impl<T> GenericTrait<T> for i32 { /* ... */ }

    // T constrains by being an argument to GenericStruct
    impl<T> Trait for GenericStruct<T> { /* ... */ }

    // Likewise, N constrains by being an argument to ConstGenericStruct
    impl<const N: usize> Trait for ConstGenericStruct<N> { /* ... */ }

    // T constrains by being in an associated type in a bound for type `U` which is
    // itself a generic parameter constraining the trait.
    impl<T, U> GenericTrait<U> for u32 where U: HasAssocType<Ty = T> { /* ... */ }

    // Like previous, except the type is `(U, isize)`. `U` appears inside the type
    // that includes `T`, and is not the type itself.
    impl<T, U> GenericStruct<U> where (U, isize): HasAssocType<Ty = T> { /* ... */ }
    }

Examples of non-constraining situations:

    #![allow(unused)]
    fn main() {
    // The rest of these are errors, since they have type or const parameters that
    // do not constrain.

    // T does not constrain since it does not appear at all.
    impl<T> Struct { /* ... */ }

    // N does not constrain for the same reason.
    impl<const N: usize> Struct { /* ... */ }

    // Usage of T inside the implementation does not constrain the impl.
    impl<T> Struct {
        fn uses_t(t: &T) { /* ... */ }
    }

    // T is used as an associated type in the bounds for U, but U does not constrain.
    impl<T, U> Struct where U: HasAssocType<Ty = T> { /* ... */ }

    // T is used in the bounds, but not as an associated type, so it does not constrain.
    impl<T, U> GenericTrait<U> for u32 where U: GenericTrait<T> {}
    }

Example of an allowed unconstraining lifetime parameter:

    #![allow(unused)]
    fn main() {
    struct Struct;
    impl<'a> Struct {}
    }

Example of a disallowed unconstraining lifetime parameter:

    #![allow(unused)]
    fn main() {
    struct Struct;
    trait HasAssocType { type Ty; }
    impl<'a> HasAssocType for Struct {
        type Ty = &'a Struct;
    }
    }

[items.impl.attributes]

## Attributes on implementations

Implementations may contain outer attributes before the `impl` keyword and inner attributes inside the brackets that contain the associated items. Inner attributes must come before any associated items. The attributes that have meaning here are `cfg`, `deprecated`, `doc`, and the lint check attributes.

[items.extern]

# External blocks

[items.extern.syntax]

Syntax
ExternBlock →
unsafe?​1 extern Abi? {
InnerAttribute*
ExternalItem*
}

ExternalItem →
OuterAttribute* (
MacroInvocationSemi
| Visibility? StaticItem
| Visibility? Function
)

[items.extern.intro]

External blocks provide declarations of items that are not defined in the current crate and are the basis of Rust’s foreign function interface. These are akin to unchecked imports.

[items.extern.allowed-kinds]

Two kinds of item declarations are allowed in external blocks: functions and statics.

[items.extern.safety]

Calling unsafe functions or accessing unsafe statics that are declared in external blocks is only allowed in an `unsafe` context.

[items.extern.namespace]

The external block defines its functions and statics in the value namespace of the module or block where it is located.

[items.extern.unsafe-required]

The `unsafe` keyword is semantically required to appear before the `extern` keyword on external blocks.

[items.extern.edition2024]

> 2024 Edition differences

> Prior to the 2024 edition, the `unsafe` keyword is optional. The `safe` and `unsafe` item qualifiers are only allowed if the external block itself is marked as `unsafe`.

[items.extern.fn]

## Functions

[items.extern.fn.body]

Functions within external blocks are declared in the same way as other Rust functions, with the exception that they must not have a body and are instead terminated by a semicolon.

[items.extern.fn.param-patterns]

Patterns are not allowed in parameters, only IDENTIFIER or `_` may be used.

[items.extern.fn.qualifiers]

The `safe` and `unsafe` function qualifiers are allowed, but other function qualifiers (e.g. `const`, `async`, `extern`) are not.

[items.extern.fn.foreign-abi]

Functions within external blocks may be called by Rust code, just like functions defined in Rust. The Rust compiler automatically translates between the Rust ABI and the foreign ABI.

[items.extern.fn.safety]

A function declared in an extern block is implicitly `unsafe` unless the `safe` function qualifier is present.

[items.extern.fn.fn-ptr]

When coerced to a function pointer, a function declared in an extern block has type `extern "abi" for<'l1, ..., 'lm> fn(A1, ..., An) -> R`, where `'l1`, … `'lm` are its lifetime parameters, `A1`, …, `An` are the declared types of its parameters, and `R` is the declared return type.

[items.extern.static]

## Statics

[items.extern.static.intro]

Statics within external blocks are declared in the same way as statics outside of external blocks, except that they do not have an expression initializing their value.

[items.extern.static.safety]

Unless a static item declared in an extern block is qualified as `safe`, it is `unsafe` to access that item, whether or not it’s mutable, because there is nothing guaranteeing that the bit pattern at the static’s memory is valid for the type it is declared with, since some arbitrary (e.g. C) code is in charge of initializing the static.

[items.extern.static.mut]

Extern statics can be either immutable or mutable just like statics outside of external blocks.

[items.extern.static.read-only]

An immutable static must be initialized before any Rust code is executed. It is not enough for the static to be initialized before Rust code reads from it. Once Rust code runs, mutating an immutable static (from inside or outside Rust) is UB, except if the mutation happens to bytes inside of an `UnsafeCell`.

[items.extern.abi]

## ABI

[items.extern.abi.intro]

The `extern` keyword can be followed by an optional ABI string. The ABI specifies the calling convention of the functions in the block. The calling convention defines a low-level interface for functions, such as how arguments are placed in registers or on the stack, how return values are passed, and who is responsible for cleaning up the stack.

> Example

>     #![allow(unused)]
>     fn main() {
>     // Interface to the Windows API.
>     unsafe extern "system" { /* ... */ }
>     }

[items.extern.abi.default]

If the ABI string is not specified, it defaults to `"C"`.

> Note

> The `extern` syntax without an explicit ABI is being phased out, so it’s better to always write the ABI explicitly.

> For more details, see Rust issue #134986.

[items.extern.abi.standard]

The following ABI strings are supported on all platforms:

[items.extern.abi.rust]

- `unsafe extern "Rust"` — The native calling convention for Rust functions and closures. This is the default when a function is declared without using `extern fn`. The Rust ABI offers no stability guarantees.

[items.extern.abi.c]

- `unsafe extern "C"` — The “C” ABI matches the default ABI chosen by the dominant C compiler for the target.

[items.extern.abi.system]

- `unsafe extern "system"` — This is equivalent to `extern "C"` except on Windows x86_32 where it is equivalent to `"stdcall"` for non-variadic functions, and equivalent to `"C"` for variadic functions.

  > Note

  > As the correct underlying ABI on Windows is target-specific, it’s best to use `extern "system"` when attempting to link Windows API functions that don’t use an explicitly defined ABI.

[items.extern.abi.unwind]

- `extern "C-unwind"` and `extern "system-unwind"` — Identical to `"C"` and `"system"`, respectively, but with different behavior when the callee unwinds (by panicking or throwing a C++ style exception).

[items.extern.abi.platform]

There are also some platform-specific ABI strings:

[items.extern.abi.cdecl]

- `unsafe extern "cdecl"` — The calling convention typically used with x86_32 C code.

  - Only available on x86_32 targets.
  - Corresponds to MSVC’s `__cdecl` and GCC and clang’s `__attribute__((cdecl))`.

  > Note

  > For details, see:

  > - https://learn.microsoft.com/en-us/cpp/cpp/cdecl
  > - https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl

[items.extern.abi.stdcall]

- `unsafe extern "stdcall"` — The calling convention typically used by the Win32 API on x86_32.

  - Only available on x86_32 targets.
  - Corresponds to MSVC’s `__stdcall` and GCC and clang’s `__attribute__((stdcall))`.

  > Note

  > For details, see:

  > - https://learn.microsoft.com/en-us/cpp/cpp/stdcall
  > - https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall

[items.extern.abi.win64]

- `unsafe extern "win64"` — The Windows x64 ABI.

  - Only available on x86_64 targets.
  - “win64” is the same as the “C” ABI on Windows x86_64 targets.
  - Corresponds to GCC and clang’s `__attribute__((ms_abi))`.

  > Note

  > For details, see:

  > - https://learn.microsoft.com/en-us/cpp/build/x64-software-conventions
  > - https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_x64_calling_convention

[items.extern.abi.sysv64]

- `unsafe extern "sysv64"` — The System V ABI.

  - Only available on x86_64 targets.
  - “sysv64” is the same as the “C” ABI on non-Windows x86_64 targets.
  - Corresponds to GCC and clang’s `__attribute__((sysv_abi))`.

  > Note

  > For details, see:

  > - https://wiki.osdev.org/System_V_ABI
  > - https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI

[items.extern.abi.aapcs]

- `unsafe extern "aapcs"` — The soft-float ABI for ARM.

  - Only available on ARM32 targets.
  - “aapcs” is the same as the “C” ABI on soft-float ARM32.
  - Corresponds to clang’s `__attribute__((pcs("aapcs")))`.

  > Note

  > For details, see:

  > - Arm Procedure Call Standard

[items.extern.abi.fastcall]

- `unsafe extern "fastcall"` — A “fast” variant of stdcall that passes some arguments in registers.

  - Only available on x86_32 targets.
  - Corresponds to MSVC’s `__fastcall` and GCC and clang’s `__attribute__((fastcall))`.

  > Note

  > For details, see:

  > - https://learn.microsoft.com/en-us/cpp/cpp/fastcall
  > - https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall

[items.extern.abi.thiscall]

- `unsafe extern "thiscall"` — The calling convention typically used on C++ class member functions on x86_32 MSVC.

  - Only available on x86_32 targets.
  - Corresponds to MSVC’s `__thiscall` and GCC and clang’s `__attribute__((thiscall))`.

  > Note

  > For details, see:

  > - https://en.wikipedia.org/wiki/X86_calling_conventions#thiscall
  > - https://learn.microsoft.com/en-us/cpp/cpp/thiscall

[items.extern.abi.efiapi]

- `unsafe extern "efiapi"` — The ABI used for UEFI functions.
  - Only available on x86 and ARM targets (32bit and 64bit).

[items.extern.abi.platform-unwind-variants]

Like `"C"` and `"system"`, most platform-specific ABI strings also have a corresponding `-unwind` variant; specifically, these are:

- `"aapcs-unwind"`
- `"cdecl-unwind"`
- `"fastcall-unwind"`
- `"stdcall-unwind"`
- `"sysv64-unwind"`
- `"thiscall-unwind"`
- `"win64-unwind"`

[items.extern.variadic]

## Variadic functions

Functions within external blocks may be variadic by specifying `...` as the last argument. The variadic parameter may optionally be specified with an identifier.

    #![allow(unused)]
    fn main() {
    unsafe extern "C" {
        unsafe fn foo(...);
        unsafe fn bar(x: i32, ...);
        unsafe fn with_name(format: *const u8, args: ...);
        // SAFETY: This function guarantees it will not access
        // variadic arguments.
        safe fn ignores_variadic_arguments(x: i32, ...);
    }
    }

> Warning

> The `safe` qualifier should not be used on a function in an `extern` block unless that function guarantees that it will not access the variadic arguments at all. Passing an unexpected number of arguments or arguments of unexpected type to a variadic function may lead to undefined behavior.

[items.extern.variadic.conventions]

Variadic parameters can only be specified within `extern` blocks with the following ABI strings or their corresponding `-unwind` variants:

- `"aapcs"`
- `"C"`
- `"cdecl"`
- `"efiapi"`
- `"system"`
- `"sysv64"`
- `"win64"`

[items.extern.attributes]

## Attributes on extern blocks

[items.extern.attributes.intro]

The following attributes control the behavior of external blocks.

[items.extern.attributes.link]

### The `link` attribute

[items.extern.attributes.link.intro]

The `link` attribute specifies the name of a native library that the compiler should link with for the items within an `extern` block.

[items.extern.attributes.link.syntax]

It uses the MetaListNameValueStr syntax to specify its inputs. The `name` key is the name of the native library to link. The `kind` key is an optional value which specifies the kind of library with the following possible values:

[items.extern.attributes.link.dylib]

- `dylib` — Indicates a dynamic library. This is the default if `kind` is not specified.

[items.extern.attributes.link.static]

- `static` — Indicates a static library.

[items.extern.attributes.link.framework]

- `framework` — Indicates a macOS framework. This is only valid for macOS targets.

[items.extern.attributes.link.raw-dylib]

- `raw-dylib` — Indicates a dynamic library where the compiler will generate an import library to link against (see `dylib` versus `raw-dylib` below for details). This is only valid for Windows targets.

[items.extern.attributes.link.name-requirement]

The `name` key must be included if `kind` is specified.

[items.extern.attributes.link.modifiers]

The optional `modifiers` argument is a way to specify linking modifiers for the library to link.

[items.extern.attributes.link.modifiers.syntax]

Modifiers are specified as a comma-delimited string with each modifier prefixed with either a `+` or `-` to indicate that the modifier is enabled or disabled, respectively.

[items.extern.attributes.link.modifiers.multiple]

Specifying multiple `modifiers` arguments in a single `link` attribute, or multiple identical modifiers in the same `modifiers` argument is not currently supported.
Example: `#[link(name = "mylib", kind = "static", modifiers = "+whole-archive")]`.

[items.extern.attributes.link.wasm_import_module]

The `wasm_import_module` key may be used to specify the WebAssembly module name for the items within an `extern` block when importing symbols from the host environment. The default module name is `env` if `wasm_import_module` is not specified.

    #[link(name = "crypto")]
    unsafe extern {
        // …
    }

    #[link(name = "CoreFoundation", kind = "framework")]
    unsafe extern {
        // …
    }

    #[link(wasm_import_module = "foo")]
    unsafe extern {
        // …
    }

[items.extern.attributes.link.empty-block]

It is valid to add the `link` attribute on an empty extern block. You can use this to satisfy the linking requirements of extern blocks elsewhere in your code (including upstream crates) instead of adding the attribute to each extern block.

[items.extern.attributes.link.modifiers.bundle]

#### Linking modifiers: `bundle`

[items.extern.attributes.link.modifiers.bundle.allowed-kinds]

This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.

[items.extern.attributes.link.modifiers.bundle.behavior]

When building a rlib or staticlib `+bundle` means that the native static library will be packed into the rlib or staticlib archive, and then retrieved from there during linking of the final binary.

[items.extern.attributes.link.modifiers.bundle.behavior-negative]

When building a rlib `-bundle` means that the native static library is registered as a dependency of that rlib “by name”, and object files from it are included only during linking of the final binary, the file search by that name is also performed during final linking.
When building a staticlib `-bundle` means that the native static library is simply not included into the archive and some higher level build system will need to add it later during linking of the final binary.

[items.extern.attributes.link.modifiers.bundle.no-effect]

This modifier has no effect when building other targets like executables or dynamic libraries.

[items.extern.attributes.link.modifiers.bundle.default]

The default for this modifier is `+bundle`.

More implementation details about this modifier can be found in `bundle` documentation for rustc.

[items.extern.attributes.link.modifiers.whole-archive]

#### Linking modifiers: `whole-archive`

[items.extern.attributes.link.modifiers.whole-archive.allowed-kinds]

This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.

[items.extern.attributes.link.modifiers.whole-archive.behavior]

`+whole-archive` means that the static library is linked as a whole archive without throwing any object files away.

[items.extern.attributes.link.modifiers.whole-archive.default]

The default for this modifier is `-whole-archive`.

More implementation details about this modifier can be found in `whole-archive` documentation for rustc.

[items.extern.attributes.link.modifiers.verbatim]

### Linking modifiers: `verbatim`

[items.extern.attributes.link.modifiers.verbatim.allowed-kinds]

This modifier is compatible with all linking kinds.

[items.extern.attributes.link.modifiers.verbatim.behavior]

`+verbatim` means that rustc itself won’t add any target-specified library prefixes or suffixes (like `lib` or `.a`) to the library name, and will try its best to ask for the same thing from the linker.

[items.extern.attributes.link.modifiers.verbatim.behavior-negative]

`-verbatim` means that rustc will either add a target-specific prefix and suffix to the library name before passing it to linker, or won’t prevent linker from implicitly adding it.

[items.extern.attributes.link.modifiers.verbatim.default]

The default for this modifier is `-verbatim`.

More implementation details about this modifier can be found in `verbatim` documentation for rustc.

[items.extern.attributes.link.kind-raw-dylib]

#### `dylib` versus `raw-dylib`

[items.extern.attributes.link.kind-raw-dylib.intro]

On Windows, linking against a dynamic library requires that an import library is provided to the linker: this is a special static library that declares all of the symbols exported by the dynamic library in such a way that the linker knows that they have to be dynamically loaded at runtime.

[items.extern.attributes.link.kind-raw-dylib.import]

Specifying `kind = "dylib"` instructs the Rust compiler to link an import library based on the `name` key. The linker will then use its normal library resolution logic to find that import library. Alternatively, specifying `kind = "raw-dylib"` instructs the compiler to generate an import library during compilation and provide that to the linker instead.

[items.extern.attributes.link.kind-raw-dylib.platform-specific]

`raw-dylib` is only supported on Windows. Using it when targeting other platforms will result in a compiler error.

[items.extern.attributes.link.import_name_type]

#### The `import_name_type` key

[items.extern.attributes.link.import_name_type.intro]

On x86 Windows, names of functions are “decorated” (i.e., have a specific prefix and/or suffix added) to indicate their calling convention. For example, a `stdcall` calling convention function with the name `fn1` that has no arguments would be decorated as `_fn1@0`. However, the PE Format does also permit names to have no prefix or be undecorated. Additionally, the MSVC and GNU toolchains use different decorations for the same calling conventions which means, by default, some Win32 functions cannot be called using the `raw-dylib` link kind via the GNU toolchain.

[items.extern.attributes.link.import_name_type.values]

To allow for these differences, when using the `raw-dylib` link kind you may also specify the `import_name_type` key with one of the following values to change how functions are named in the generated import library:

- `decorated`: The function name will be fully-decorated using the MSVC toolchain format.
- `noprefix`: The function name will be decorated using the MSVC toolchain format, but skipping the leading `?`, `@`, or optionally `_`.
- `undecorated`: The function name will not be decorated.

[items.extern.attributes.link.import_name_type.default]

If the `import_name_type` key is not specified, then the function name will be fully-decorated using the target toolchain’s format.

[items.extern.attributes.link.import_name_type.variables]

Variables are never decorated and so the `import_name_type` key has no effect on how they are named in the generated import library.

[items.extern.attributes.link.import_name_type.platform-specific]

The `import_name_type` key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error.

[items.extern.attributes.link_name]

### The `link_name` attribute

[items.extern.attributes.link_name.intro]

The `link_name` attribute may be applied to declarations inside an `extern` block to specify the symbol to import for the given function or static.

> Example

>     #![allow(unused)]
>     fn main() {
>     unsafe extern "C" {
>         #[link_name = "actual_symbol_name"]
>         safe fn name_in_rust();
>     }
>     }

[items.extern.attributes.link_name.syntax]

The `link_name` attribute uses the MetaNameValueStr syntax.

[items.extern.attributes.link_name.allowed-positions]

The `link_name` attribute may only be applied to a function or static item in an `extern` block.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[items.extern.attributes.link_name.duplicates]

Only the last use of `link_name` on an item has effect.

> Note

> `rustc` lints against any use preceding the last. This may become an error in the future.

[items.extern.attributes.link_name.link_ordinal]

The `link_name` attribute may not be used with the `link_ordinal` attribute.

[items.extern.attributes.link_ordinal]

### The `link_ordinal` attribute

[items.extern.attributes.link_ordinal.intro]

The `link_ordinal` attribute can be applied on declarations inside an `extern` block to indicate the numeric ordinal to use when generating the import library to link against. An ordinal is a unique number per symbol exported by a dynamic library on Windows and can be used when the library is being loaded to find that symbol rather than having to look it up by name.

> Warning

> `link_ordinal` should only be used in cases where the ordinal of the symbol is known to be stable: if the ordinal of a symbol is not explicitly set when its containing binary is built then one will be automatically assigned to it, and that assigned ordinal may change between builds of the binary.

    #![allow(unused)]
    fn main() {
    #[cfg(all(windows, target_arch = "x86"))]
    #[link(name = "exporter", kind = "raw-dylib")]
    unsafe extern "stdcall" {
        #[link_ordinal(15)]
        safe fn imported_function_stdcall(i: i32);
    }
    }

[items.extern.attributes.link_ordinal.allowed-kinds]

This attribute is only used with the `raw-dylib` linking kind. Using any other kind will result in a compiler error.

[items.extern.attributes.link_ordinal.exclusive]

Using this attribute with the `link_name` attribute will result in a compiler error.

[items.extern.attributes.fn-parameters]

### Attributes on function parameters

Attributes on extern function parameters follow the same rules and restrictions as regular function parameters.

1. Starting with the 2024 Edition, the `unsafe` keyword is required semantically. ↩

[items.generics]

# Generic parameters

[items.generics.syntax]

Syntax
GenericParams → < ( GenericParam ( , GenericParam )* ,? )? >

GenericParam → OuterAttribute* ( LifetimeParam | TypeParam | ConstParam )

LifetimeParam → Lifetime ( : LifetimeBounds )?

TypeParam → IDENTIFIER ( : TypeParamBounds? )? ( = Type )?

ConstParam →
const IDENTIFIER : Type
( = ( BlockExpression | IDENTIFIER | -? LiteralExpression ) )?

[items.generics.syntax.intro]

Functions, type aliases, structs, enumerations, unions, traits, and implementations may be parameterized by types, constants, and lifetimes. These parameters are listed in angle brackets (`<...>`), usually immediately after the name of the item and before its definition. For implementations, which don’t have a name, they come directly after `impl`.

[items.generics.syntax.decl-order]
Tests
Tests with this rule:

- tests/ui/const-generics/argument_order.rs

The order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed.

[items.generics.syntax.duplicate-params]

The same parameter name may not be declared more than once in a GenericParams list.

Some examples of items with type, const, and lifetime parameters:

    #![allow(unused)]
    fn main() {
    fn foo<'a, T>() {}
    trait A<U> {}
    struct Ref<'a, T> where T: 'a { r: &'a T }
    struct InnerArray<T, const N: usize>([T; N]);
    struct EitherOrderWorks<const N: bool, U>(U);
    }

[items.generics.syntax.scope]

Generic parameters are in scope within the item definition where they are declared. They are not in scope for items declared within the body of a function as described in item declarations. See generic parameter scopes for more details.

[items.generics.builtin-generic-types]

References, raw pointers, arrays, slices, tuples, and function pointers have lifetime or type parameters as well, but are not referred to with path syntax.

[items.generics.invalid-lifetimes]

`'_` and `'static` are not valid lifetime parameter names.

[items.generics.const]

### Const generics

[items.generics.const.intro]

Const generic parameters allow items to be generic over constant values.

[items.generics.const.namespace]

The const identifier introduces a name in the value namespace for the constant parameter, and all instances of the item must be instantiated with a value of the given type.

[items.generics.const.allowed-types]

The only allowed types of const parameters are `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`.

[items.generics.const.usage]

Const parameters can be used anywhere a const item can be used, with the exception that when used in a type or array repeat expression, it must be standalone (as described below). That is, they are allowed in the following places:

1. As an applied const to any type which forms a part of the signature of the item in question.
2. As part of a const expression used to define an associated const, or as a parameter to an associated type.
3. As a value in any runtime expression in the body of any functions in the item.
4. As a parameter to any type used in the body of any functions in the item.
5. As a part of the type of any fields in the item.

    #![allow(unused)]
    fn main() {
    // Examples where const generic parameters can be used.

    // Used in the signature of the item itself.
    fn foo<const N: usize>(arr: [i32; N]) {
        // Used as a type within a function body.
        let x: [i32; N];
        // Used as an expression.
        println!("{}", N * 2);
    }

    // Used as a field of a struct.
    struct Foo<const N: usize>([i32; N]);

    impl<const N: usize> Foo<N> {
        // Used as an associated constant.
        const CONST: usize = N * 4;
    }

    trait Trait {
        type Output;
    }

    impl<const N: usize> Trait for Foo<N> {
        // Used as an associated type.
        type Output = [i32; N];
    }
    }

    #![allow(unused)]
    fn main() {
    // Examples where const generic parameters cannot be used.
    fn foo<const N: usize>() {
        // Cannot use in item definitions within a function body.
        const BAD_CONST: [usize; N] = [1; N];
        static BAD_STATIC: [usize; N] = [1; N];
        fn inner(bad_arg: [usize; N]) {
            let bad_value = N * 2;
        }
        type BadAlias = [usize; N];
        struct BadStruct([usize; N]);
    }
    }

[items.generics.const.standalone]

As a further restriction, const parameters may only appear as a standalone argument inside of a type or array repeat expression. In those contexts, they may only be used as a single segment path expression, possibly inside a block (such as `N` or `{N}`). That is, they cannot be combined with other expressions.

    #![allow(unused)]
    fn main() {
    // Examples where const parameters may not be used.

    // Not allowed to combine in other expressions in types, such as the
    // arithmetic expression in the return type here.
    fn bad_function<const N: usize>() -> [u8; {N + 1}] {
        // Similarly not allowed for array repeat expressions.
        [1; {N + 1}]
    }
    }

[items.generics.const.argument]

A const argument in a path specifies the const value to use for that item.

[items.generics.const.argument.const-expr]

The argument must either be an inferred const or be a const expression of the type ascribed to the const parameter. The const expression must be a block expression (surrounded with braces) unless it is a single path segment (an IDENTIFIER) or a literal (with a possibly leading `-` token).

> Note

> This syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type.

    #![allow(unused)]
    fn main() {
    struct S<const N: i64>;
    const C: i64 = 1;
    fn f<const N: i64>() -> S<N> { S }

    let _ = f::<1>(); // Literal.
    let _ = f::<-1>(); // Negative literal.
    let _ = f::<{ 1 + 2 }>(); // Constant expression.
    let _ = f::<C>(); // Single segment path.
    let _ = f::<{ C + 1 }>(); // Constant expression.
    let _: S<1> = f::<_>(); // Inferred const.
    let _: S<1> = f::<(((_)))>(); // Inferred const.
    }

> Note

> In a generic argument list, an inferred const is parsed as an inferred type but then semantically treated as a separate kind of const generic argument.

[items.generics.const.inferred]
Tests
Tests with this rule:

- tests/ui/const-generics/generic_arg_infer/paren_infer.rs

Where a const argument is expected, an `_` (optionally surrounded by any number of matching parentheses), called the inferred const (path rules, array expression rules), can be used instead. This asks the compiler to infer the const argument if possible based on surrounding information.

    #![allow(unused)]
    fn main() {
    fn make_buf<const N: usize>() -> [u8; N] {
        [0; _]
        //  ^ Infers `N`.
    }
    let _: [u8; 1024] = make_buf::<_>();
    //                             ^ Infers `1024`.
    }

> Note

> An inferred const is not semantically an expression and so is not accepted within braces.

>     #![allow(unused)]
>     fn main() {
>     fn f<const N: usize>() -> [u8; N] { [0; _] }
>     let _: [_; 1] = f::<{ _ }>();
>     //                    ^ ERROR `_` not allowed here
>     }

[items.generics.const.inferred.constraint]

The inferred const cannot be used in item signatures.

    #![allow(unused)]
    fn main() {
    fn f<const N: usize>(x: [u8; N]) -> [u8; _] { x }
    //                                       ^ ERROR not allowed
    }

[items.generics.const.type-ambiguity]

When there is ambiguity if a generic argument could be resolved as either a type or const argument, it is always resolved as a type. Placing the argument in a block expression can force it to be interpreted as a const argument.

    #![allow(unused)]
    fn main() {
    type N = u32;
    struct Foo<const N: usize>;
    // The following is an error, because `N` is interpreted as the type alias `N`.
    fn foo<const N: usize>() -> Foo<N> { todo!() } // ERROR
    // Can be fixed by wrapping in braces to force it to be interpreted as the `N`
    // const parameter:
    fn bar<const N: usize>() -> Foo<{ N }> { todo!() } // ok
    }

[items.generics.const.variance]

Unlike type and lifetime parameters, const parameters can be declared without being used inside of a parameterized item, with the exception of implementations as described in generic implementations:

    #![allow(unused)]
    fn main() {
    // ok
    struct Foo<const N: usize>;
    enum Bar<const M: usize> { A, B }

    // ERROR: unused parameter
    struct Baz<T>;
    struct Biz<'a>;
    struct Unconstrained;
    impl<const N: usize> Unconstrained {}
    }

[items.generics.const.exhaustiveness]

When resolving a trait bound obligation, the exhaustiveness of all implementations of const parameters is not considered when determining if the bound is satisfied. For example, in the following, even though all possible const values for the `bool` type are implemented, it is still an error that the trait bound is not satisfied:

    #![allow(unused)]
    fn main() {
    struct Foo<const B: bool>;
    trait Bar {}
    impl Bar for Foo<true> {}
    impl Bar for Foo<false> {}

    fn needs_bar(_: impl Bar) {}
    fn generic<const B: bool>() {
        let v = Foo::<B>;
        needs_bar(v); // ERROR: trait bound `Foo<B>: Bar` is not satisfied
    }
    }

[items.generics.where]

## Where clauses

[items.generics.where.syntax]

Syntax
WhereClause → where ( WhereClauseItem , )* WhereClauseItem?

WhereClauseItem →
LifetimeWhereClauseItem
| TypeBoundWhereClauseItem

LifetimeWhereClauseItem → Lifetime : LifetimeBounds

TypeBoundWhereClauseItem → ForLifetimes? Type : TypeParamBounds?

[items.generics.where.intro]

Where clauses provide another way to specify bounds on type and lifetime parameters as well as a way to specify bounds on types that aren’t type parameters.

[items.generics.where.higher-ranked-lifetimes]

The `for` keyword can be used to introduce higher-ranked lifetimes. It only allows LifetimeParam parameters.

    #![allow(unused)]
    fn main() {
    struct A<T>
    where
        T: Iterator,            // Could use A<T: Iterator> instead
        T::Item: Copy,          // Bound on an associated type
        String: PartialEq<T>,   // Bound on `String`, using the type parameter
        i32: Default,           // Allowed, but not useful
    {
        f: T,
    }
    }

[items.generics.attributes]

## Attributes

Generic lifetime and type parameters allow attributes on them. There are no built-in attributes that do anything in this position, although custom derive attributes may give meaning to it.

This example shows using a custom derive attribute to modify the meaning of a generic parameter.

    // Assume that the derive for MyFlexibleClone declared `my_flexible_clone` as
    // an attribute it understands.
    #[derive(MyFlexibleClone)]
    struct Foo<#[my_flexible_clone(unbounded)] H> {
        a: *const H
    }

[items.associated]

# Associated items

[items.associated.syntax]

Syntax
AssociatedItem →
OuterAttribute* (
MacroInvocationSemi
| ( Visibility? ( TypeAlias | ConstantItem | Function ) )
)

[items.associated.intro]

Associated Items are the items declared in traits or defined in implementations. They are called this because they are defined on an associate type — the type in the implementation.

[items.associated.kinds]

They are a subset of the kinds of items you can declare in a module. Specifically, there are associated functions (including methods), associated types, and associated constants.

[items.associated.related]

Associated items are useful when the associated item is logically related to the associating item. For example, the `is_some` method on `Option` is intrinsically related to Options, so should be associated.

[items.associated.decl-def]

Every associated item kind comes in two varieties: definitions that contain the actual implementation and declarations that declare signatures for definitions.

[items.associated.trait-items]

It is the declarations that make up the contract of traits and what is available on generic types.

[items.associated.fn]

## Associated functions and methods

[items.associated.fn.intro]

Associated functions are functions associated with a type.

[items.associated.fn.decl]

An associated function declaration declares a signature for an associated function definition. It is written as a function item, except the function body is replaced with a `;`.

[items.associated.name]

The identifier is the name of the function.

[items.associated.same-signature]

The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations’s.

[items.associated.fn.def]

An associated function definition defines a function associated with another type. It is written the same as a function item.

> Note

> A common example is an associated function named `new` that returns a value of the type with which it is associated.

    struct Struct {
        field: i32
    }

    impl Struct {
        fn new() -> Struct {
            Struct {
                field: 0i32
            }
        }
    }

    fn main () {
        let _struct = Struct::new();
    }

[items.associated.fn.qualified-self]

When the associated function is declared on a trait, the function can also be called with a path that is a path to the trait appended by the name of the trait. When this happens, it is substituted for `<_ as Trait>::function_name`.

    #![allow(unused)]
    fn main() {
    trait Num {
        fn from_i32(n: i32) -> Self;
    }

    impl Num for f64 {
        fn from_i32(n: i32) -> f64 { n as f64 }
    }

    // These 4 are all equivalent in this case.
    let _: f64 = Num::from_i32(42);
    let _: f64 = <_ as Num>::from_i32(42);
    let _: f64 = <f64 as Num>::from_i32(42);
    let _: f64 = f64::from_i32(42);
    }

[items.associated.fn.method]

### Methods

[items.associated.fn.method.intro]

Associated functions whose first parameter is named `self` are called methods and may be invoked using the method call operator, for example, `x.foo()`, as well as the usual function call notation.

[items.associated.fn.method.self-ty]

If the type of the `self` parameter is specified, it is limited to types resolving to one generated by the following grammar (where `'lt` denotes some arbitrary lifetime):

    P = &'lt S | &'lt mut S | Box<S> | Rc<S> | Arc<S> | Pin<P>
    S = Self | P

The `Self` terminal in this grammar denotes a type resolving to the implementing type. This can also include the contextual type alias `Self`, other type aliases, or associated type projections resolving to the implementing type.

    #![allow(unused)]
    fn main() {
    use std::rc::Rc;
    use std::sync::Arc;
    use std::pin::Pin;
    // Examples of methods implemented on struct `Example`.
    struct Example;
    type Alias = Example;
    trait Trait { type Output; }
    impl Trait for Example { type Output = Example; }
    impl Example {
        fn by_value(self: Self) {}
        fn by_ref(self: &Self) {}
        fn by_ref_mut(self: &mut Self) {}
        fn by_box(self: Box<Self>) {}
        fn by_rc(self: Rc<Self>) {}
        fn by_arc(self: Arc<Self>) {}
        fn by_pin(self: Pin<&Self>) {}
        fn explicit_type(self: Arc<Example>) {}
        fn with_lifetime<'a>(self: &'a Self) {}
        fn nested<'a>(self: &mut &'a Arc<Rc<Box<Alias>>>) {}
        fn via_projection(self: <Example as Trait>::Output) {}
    }
    }

[associated.fn.method.self-pat-shorthands]

Shorthand syntax can be used without specifying a type, which have the following equivalents:

Shorthand | Equivalent
--- | ---
`self` | `self: Self`
`&'lifetime self` | `self: &'lifetime Self`
`&'lifetime mut self` | `self: &'lifetime mut Self`

> Note

> Lifetimes can be, and usually are, elided with this shorthand.

[associated.fn.method.self-pat-mut]

If the `self` parameter is prefixed with `mut`, it becomes a mutable variable, similar to regular parameters using a `mut` identifier pattern. For example:

    #![allow(unused)]
    fn main() {
    trait Changer: Sized {
        fn change(mut self) {}
        fn modify(mut self: Box<Self>) {}
    }
    }

As an example of methods on a trait, consider the following:

    #![allow(unused)]
    fn main() {
    type Surface = i32;
    type BoundingBox = i32;
    trait Shape {
        fn draw(&self, surface: Surface);
        fn bounding_box(&self) -> BoundingBox;
    }
    }

This defines a trait with two methods. All values that have implementations of this trait while the trait is in scope can have their `draw` and `bounding_box` methods called.

    #![allow(unused)]
    fn main() {
    type Surface = i32;
    type BoundingBox = i32;
    trait Shape {
        fn draw(&self, surface: Surface);
        fn bounding_box(&self) -> BoundingBox;
    }

    struct Circle {
        // ...
    }

    impl Shape for Circle {
        // ...
      fn draw(&self, _: Surface) {}
      fn bounding_box(&self) -> BoundingBox { 0i32 }
    }

    impl Circle {
        fn new() -> Circle { Circle{} }
    }

    let circle_shape = Circle::new();
    let bounding_box = circle_shape.bounding_box();
    }

[items.associated.fn.params.edition2018]

> 2018 Edition differences

> In the 2015 edition, it is possible to declare trait methods with anonymous parameters (e.g. `fn foo(u8)`). This is deprecated and an error as of the 2018 edition. All parameters must have an argument name.

[items.associated.fn.param-attributes]

#### Attributes on method parameters

Attributes on method parameters follow the same rules and restrictions as regular function parameters.

[items.associated.type]

## Associated types

[items.associated.type.intro]

Associated types are type aliases associated with another type.

[items.associated.type.restrictions]

Associated types cannot be defined in inherent implementations nor can they be given a default implementation in traits.

[items.associated.type.decl]

An associated type declaration declares a signature for associated type definitions. It is written in one of the following forms, where `Assoc` is the name of the associated type, `Params` is a comma-separated list of type, lifetime or const parameters, `Bounds` is a plus-separated list of trait bounds that the associated type must meet, and `WhereBounds` is a comma-separated list of bounds that the parameters must meet:

    type Assoc;
    type Assoc: Bounds;
    type Assoc<Params>;
    type Assoc<Params>: Bounds;
    type Assoc<Params> where WhereBounds;
    type Assoc<Params>: Bounds where WhereBounds;

[items.associated.type.name]

The identifier is the name of the declared type alias.

[items.associated.type.impl-fulfillment]

The optional trait bounds must be fulfilled by the implementations of the type alias.

[items.associated.type.sized]

There is an implicit `Sized` bound on associated types that can be relaxed using the special `?Sized` bound.

[items.associated.type.def]

An associated type definition defines a type alias for the implementation of a trait on a type.

[items.associated.type.def.restriction]

They are written similarly to an associated type declaration, but cannot contain `Bounds`, but instead must contain a `Type`:

    type Assoc = Type;
    type Assoc<Params> = Type; // the type `Type` here may reference `Params`
    type Assoc<Params> = Type where WhereBounds;
    type Assoc<Params> where WhereBounds = Type; // deprecated, prefer the form above

[items.associated.type.alias]

If a type `Item` has an associated type `Assoc` from a trait `Trait`, then `<Item as Trait>::Assoc` is a type that is an alias of the type specified in the associated type definition.

[items.associated.type.param]

Furthermore, if `Item` is a type parameter, then `Item::Assoc` can be used in type parameters.

[items.associated.type.generic]

Associated types may include generic parameters and where clauses; these are often referred to as generic associated types, or GATs. If the type `Thing` has an associated type `Item` from a trait `Trait` with the generics `<'a>` , the type can be named like `<Thing as Trait>::Item<'x>`, where `'x` is some lifetime in scope. In this case, `'x` will be used wherever `'a` appears in the associated type definitions on impls.

    trait AssociatedType {
        // Associated type declaration
        type Assoc;
    }

    struct Struct;

    struct OtherStruct;

    impl AssociatedType for Struct {
        // Associated type definition
        type Assoc = OtherStruct;
    }

    impl OtherStruct {
        fn new() -> OtherStruct {
            OtherStruct
        }
    }

    fn main() {
        // Usage of the associated type to refer to OtherStruct as <Struct as AssociatedType>::Assoc
        let _other_struct: OtherStruct = <Struct as AssociatedType>::Assoc::new();
    }

An example of associated types with generics and where clauses:

    struct ArrayLender<'a, T>(&'a mut [T; 16]);

    trait Lend {
        // Generic associated type declaration
        type Lender<'a> where Self: 'a;
        fn lend<'a>(&'a mut self) -> Self::Lender<'a>;
    }

    impl<T> Lend for [T; 16] {
        // Generic associated type definition
        type Lender<'a> = ArrayLender<'a, T> where Self: 'a;

        fn lend<'a>(&'a mut self) -> Self::Lender<'a> {
            ArrayLender(self)
        }
    }

    fn borrow<'a, T: Lend>(array: &'a mut T) -> <T as Lend>::Lender<'a> {
        array.lend()
    }

    fn main() {
        let mut array = [0usize; 16];
        let lender = borrow(&mut array);
    }

### Associated types container example

Consider the following example of a `Container` trait. Notice that the type is available for use in the method signatures:

    #![allow(unused)]
    fn main() {
    trait Container {
        type E;
        fn empty() -> Self;
        fn insert(&mut self, elem: Self::E);
    }
    }

In order for a type to implement this trait, it must not only provide implementations for every method, but it must specify the type `E`. Here’s an implementation of `Container` for the standard library type `Vec`:

    #![allow(unused)]
    fn main() {
    trait Container {
        type E;
        fn empty() -> Self;
        fn insert(&mut self, elem: Self::E);
    }
    impl<T> Container for Vec<T> {
        type E = T;
        fn empty() -> Vec<T> { Vec::new() }
        fn insert(&mut self, x: T) { self.push(x); }
    }
    }

### Relationship between `Bounds` and `WhereBounds`

In this example:

    #![allow(unused)]
    fn main() {
    use std::fmt::Debug;
    trait Example {
        type Output<T>: Ord where T: Debug;
    }
    }

Given a reference to the associated type like `<X as Example>::Output<Y>`, the associated type itself must be `Ord`, and the type `Y` must be `Debug`.

[items.associated.type.generic-where-clause]

### Required where clauses on generic associated types

[items.associated.type.generic-where-clause.intro]

Generic associated type declarations on traits currently may require a list of where clauses, dependent on functions in the trait and how the GAT is used. These rules may be loosened in the future; updates can be found on the generic associated types initiative repository.

[items.associated.type.generic-where-clause.valid-fn]

In a few words, these where clauses are required in order to maximize the allowed definitions of the associated type in impls. To do this, any clauses that can be proven to hold on functions (using the parameters of the function or trait) where a GAT appears as an input or output must also be written on the GAT itself.

    #![allow(unused)]
    fn main() {
    trait LendingIterator {
        type Item<'x> where Self: 'x;
        fn next<'a>(&'a mut self) -> Self::Item<'a>;
    }
    }

In the above, on the `next` function, we can prove that `Self: 'a`, because of the implied bounds from `&'a mut self`; therefore, we must write the equivalent bound on the GAT itself: `where Self: 'x`.

[items.associated.type.generic-where-clause.intersection]

When there are multiple functions in a trait that use the GAT, then the intersection of the bounds from the different functions are used, rather than the union.

    #![allow(unused)]
    fn main() {
    trait Check<T> {
        type Checker<'x>;
        fn create_checker<'a>(item: &'a T) -> Self::Checker<'a>;
        fn do_check(checker: Self::Checker<'_>);
    }
    }

In this example, no bounds are required on the `type Checker<'a>;`. While we know that `T: 'a` on `create_checker`, we do not know that on `do_check`. However, if `do_check` was commented out, then the `where T: 'x` bound would be required on `Checker`.

[items.associated.type.generic-where-clause.forward]

The bounds on associated types also propagate required where clauses.

    #![allow(unused)]
    fn main() {
    trait Iterable {
        type Item<'a> where Self: 'a;
        type Iterator<'a>: Iterator<Item = Self::Item<'a>> where Self: 'a;
        fn iter<'a>(&'a self) -> Self::Iterator<'a>;
    }
    }

Here, `where Self: 'a` is required on `Item` because of `iter`. However, `Item` is used in the bounds of `Iterator`, the `where Self: 'a` clause is also required there.

[items.associated.type.generic-where-clause.static]

Finally, any explicit uses of `'static` on GATs in the trait do not count towards the required bounds.

    #![allow(unused)]
    fn main() {
    trait StaticReturn {
        type Y<'a>;
        fn foo(&self) -> Self::Y<'static>;
    }
    }

[items.associated.const]

## Associated constants

[items.associated.const.intro]

Associated constants are constants associated with a type.

[items.associated.const.decl]

An associated constant declaration declares a signature for associated constant definitions. It is written as `const`, then an identifier, then `:`, then a type, finished by a `;`.

[items.associated.const.name]

The identifier is the name of the constant used in the path. The type is the type that the definition has to implement.

[items.associated.const.def]

An associated constant definition defines a constant associated with a type. It is written the same as a constant item.

[items.associated.const.eval]

Associated constant definitions undergo constant evaluation only when referenced. Further, definitions that include generic parameters are evaluated after monomorphization.

    struct Struct;
    struct GenericStruct<const ID: i32>;

    impl Struct {
        // Definition not immediately evaluated
        const PANIC: () = panic!("compile-time panic");
    }

    impl<const ID: i32> GenericStruct<ID> {
        // Definition not immediately evaluated
        const NON_ZERO: () = if ID == 0 {
            panic!("contradiction")
        };
    }

    fn main() {
        // Referencing Struct::PANIC causes compilation error
        let _ = Struct::PANIC;

        // Fine, ID is not 0
        let _ = GenericStruct::<1>::NON_ZERO;

        // Compilation error from evaluating NON_ZERO with ID=0
        let _ = GenericStruct::<0>::NON_ZERO;
    }

### Associated constants examples

A basic example:

    trait ConstantId {
        const ID: i32;
    }

    struct Struct;

    impl ConstantId for Struct {
        const ID: i32 = 1;
    }

    fn main() {
        assert_eq!(1, Struct::ID);
    }

Using default values:

    trait ConstantIdDefault {
        const ID: i32 = 1;
    }

    struct Struct;
    struct OtherStruct;

    impl ConstantIdDefault for Struct {}

    impl ConstantIdDefault for OtherStruct {
        const ID: i32 = 5;
    }

    fn main() {
        assert_eq!(1, Struct::ID);
        assert_eq!(5, OtherStruct::ID);
    }

[attributes]

# Attributes

[attributes.syntax]

Syntax
InnerAttribute → # ! [ Attr ]

OuterAttribute → # [ Attr ]

Attr →
SimplePath AttrInput?
| unsafe ( SimplePath AttrInput? )

AttrInput →
DelimTokenTree
| = Expression

[attributes.intro]

An attribute is a general, free-form metadatum that is interpreted according to name, convention, language, and compiler version. Attributes are modeled on Attributes in ECMA-335, with the syntax coming from ECMA-334 (C#).

[attributes.inner]

Inner attributes, written with a bang (`!`) after the hash (`#`), apply to the form that the attribute is declared within.

> Example

>     #![allow(unused)]
>     fn main() {
>     // General metadata applied to the enclosing module or crate.
>     #![crate_type = "lib"]

>     // Inner attribute applies to the entire function.
>     fn some_unused_variables() {
>       #![allow(unused_variables)]

>       let x = ();
>       let y = ();
>       let z = ();
>     }
>     }

[attributes.outer]

Outer attributes, written without the bang after the hash, apply to the form that follows the attribute.

> Example

>     #![allow(unused)]
>     fn main() {
>     // A function marked as a unit test
>     #[test]
>     fn test_foo() {
>         /* ... */
>     }

>     // A conditionally-compiled module
>     #[cfg(target_os = "linux")]
>     mod bar {
>         /* ... */
>     }

>     // A lint attribute used to suppress a warning/error
>     #[allow(non_camel_case_types)]
>     type int8_t = i8;
>     }

[attributes.input]

The attribute consists of a path to the attribute, followed by an optional delimited token tree whose interpretation is defined by the attribute. Attributes other than macro attributes also allow the input to be an equals sign (`=`) followed by an expression. See the meta item syntax below for more details.

[attributes.safety]

An attribute may be unsafe to apply. To avoid undefined behavior when using these attributes, certain obligations that cannot be checked by the compiler must be met. To assert these have been, the attribute is wrapped in `unsafe(..)`, e.g. `#[unsafe(no_mangle)]`.

The following attributes are unsafe:

- `export_name`
- `link_section`
- `naked`
- `no_mangle`

[attributes.kind]

Attributes can be classified into the following kinds:

- Built-in attributes
- Proc macro attributes
- Derive macro helper attributes
- Tool attributes

[attributes.allowed-position]

Attributes may be applied to many forms in the language:

- All item declarations accept outer attributes while external blocks, functions, implementations, and modules accept inner attributes.
- Most statements accept outer attributes (see Expression Attributes for limitations on expression statements).
- Block expressions accept outer and inner attributes, but only when they are the outer expression of an expression statement or the final expression of another block expression.
- Enum variants and struct and union fields accept outer attributes.
- Match expression arms accept outer attributes.
- Generic lifetime or type parameter accept outer attributes.
- Expressions accept outer attributes in limited situations, see Expression Attributes for details.
- Function, closure and function pointer parameters accept outer attributes. This includes attributes on variadic parameters denoted with `...` in function pointers and external blocks.
- Inline assembly template strings and operands accept outer attributes. Only certain attributes are accepted semantically; for details, see asm.attributes.supported-attributes.

[attributes.meta]

## Meta item attribute syntax

[attributes.meta.intro]

A “meta item” is the syntax used for the Attr rule by most built-in attributes. It has the following grammar:

[attributes.meta.syntax]

Syntax
MetaItem →
SimplePath
| SimplePath = Expression
| SimplePath ( MetaSeq? )

MetaSeq →
MetaItemInner ( , MetaItemInner )* ,?

MetaItemInner →
MetaItem
| Expression

[attributes.meta.literal-expr]

Expressions in meta items must macro-expand to literal expressions, which must not include integer or float type suffixes. Expressions which are not literal expressions will be syntactically accepted (and can be passed to proc-macros), but will be rejected after parsing.

[attributes.meta.order]

Note that if the attribute appears within another macro, it will be expanded after that outer macro. For example, the following code will expand the `Serialize` proc-macro first, which must preserve the `include_str!` call in order for it to be expanded:

    #[derive(Serialize)]
    struct Foo {
        #[doc = include_str!("x.md")]
        x: u32
    }

[attributes.meta.order-macro]

Additionally, macros in attributes will be expanded only after all other attributes applied to the item:

    #[macro_attr1] // expanded first
    #[doc = mac!()] // `mac!` is expanded fourth.
    #[macro_attr2] // expanded second
    #[derive(MacroDerive1, MacroDerive2)] // expanded third
    fn foo() {}

[attributes.meta.builtin]

Various built-in attributes use different subsets of the meta item syntax to specify their inputs. The following grammar rules show some commonly used forms:

[attributes.meta.builtin.syntax]

Syntax
MetaWord →
IDENTIFIER

MetaNameValueStr →
IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL )

MetaListPaths →
IDENTIFIER ( ( SimplePath ( , SimplePath )* ,? )? )

MetaListIdents →
IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER )* ,? )? )

MetaListNameValueStr →
IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr )* ,? )? )

Some examples of meta items are:

Style | Example
--- | ---
MetaWord | `no_std`
MetaNameValueStr | `doc = "example"`
MetaListPaths | `allow(unused, clippy::inline_always)`
MetaListIdents | `macro_use(foo, bar)`
MetaListNameValueStr | `link(name = "CoreFoundation", kind = "framework")`

[attributes.activity]

## Active and inert attributes

[attributes.activity.intro]

An attribute is either active or inert. During attribute processing, active attributes remove themselves from the form they are on while inert attributes stay on.

The `cfg` and `cfg_attr` attributes are active. Attribute macros are active. All other attributes are inert.

[attributes.tool]

## Tool attributes

[attributes.tool.intro]

The compiler may allow attributes for external tools where each tool resides in its own module in the tool prelude. The first segment of the attribute path is the name of the tool, with one or more additional segments whose interpretation is up to the tool.

[attributes.tool.ignored]

When a tool is not in use, the tool’s attributes are accepted without a warning. When the tool is in use, the tool is responsible for processing and interpretation of its attributes.

[attributes.tool.prelude]

Tool attributes are not available if the `no_implicit_prelude` attribute is used.

    #![allow(unused)]
    fn main() {
    // Tells the rustfmt tool to not format the following element.
    #[rustfmt::skip]
    struct S {
    }

    // Controls the "cyclomatic complexity" threshold for the clippy tool.
    #[clippy::cyclomatic_complexity = "100"]
    pub fn f() {}
    }

> Note

> `rustc` currently recognizes the tools “clippy”, “rustfmt”, “diagnostic”, “miri”, and “rust_analyzer”.

[attributes.builtin]

## Built-in attributes index

The following is an index of all built-in attributes.

- Conditional compilation

  - `cfg` — Controls conditional compilation.
  - `cfg_attr` — Conditionally includes attributes.

- Testing

  - `test` — Marks a function as a test.
  - `ignore` — Disables a test function.
  - `should_panic` — Indicates a test should generate a panic.

- Derive

  - `derive` — Automatic trait implementations.
  - `automatically_derived` — Marker for implementations created by `derive`.

- Macros

  - `macro_export` — Exports a `macro_rules` macro for cross-crate usage.
  - `macro_use` — Expands macro visibility, or imports macros from other crates.
  - `proc_macro` — Defines a function-like macro.
  - `proc_macro_derive` — Defines a derive macro.
  - `proc_macro_attribute` — Defines an attribute macro.

- Diagnostics

  - `allow`, `expect`, `warn`, `deny`, `forbid` — Alters the default lint level.
  - `deprecated` — Generates deprecation notices.
  - `must_use` — Generates a lint for unused values.
  - `diagnostic::on_unimplemented` — Hints the compiler to emit a certain error message if a trait is not implemented.
  - `diagnostic::do_not_recommend` — Hints the compiler to not show a certain trait impl in error messages.

- ABI, linking, symbols, and FFI

  - `link` — Specifies a native library to link with an `extern` block.
  - `link_name` — Specifies the name of the symbol for functions or statics in an `extern` block.
  - `link_ordinal` — Specifies the ordinal of the symbol for functions or statics in an `extern` block.
  - `no_link` — Prevents linking an extern crate.
  - `repr` — Controls type layout.
  - `crate_type` — Specifies the type of crate (library, executable, etc.).
  - `no_main` — Disables emitting the `main` symbol.
  - `export_name` — Specifies the exported symbol name for a function or static.
  - `link_section` — Specifies the section of an object file to use for a function or static.
  - `no_mangle` — Disables symbol name encoding.
  - `used` — Forces the compiler to keep a static item in the output object file.
  - `crate_name` — Specifies the crate name.

- Code generation

  - `inline` — Hint to inline code.
  - `cold` — Hint that a function is unlikely to be called.
  - `naked` — Prevent the compiler from emitting a function prologue and epilogue.
  - `no_builtins` — Disables use of certain built-in functions.
  - `target_feature` — Configure platform-specific code generation.
  - `track_caller` — Pass the parent call location to `std::panic::Location::caller()`.
  - `instruction_set` — Specify the instruction set used to generate a function’s code.

- Documentation

  - `doc` — Specifies documentation. See The Rustdoc Book for more information. Doc comments are transformed into `doc` attributes.

- Preludes

  - `no_std` — Removes std from the prelude.
  - `no_implicit_prelude` — Disables prelude lookups within a module.

- Modules

  - `path` — Specifies the filename for a module.

- Limits

  - `recursion_limit` — Sets the maximum recursion limit for certain compile-time operations.
  - `type_length_limit` — Sets the maximum size of a polymorphic type.

- Runtime

  - `panic_handler` — Sets the function to handle panics.
  - `global_allocator` — Sets the global memory allocator.
  - `windows_subsystem` — Specifies the windows subsystem to link with.

- Features

  - `feature` — Used to enable unstable or experimental compiler features. See The Unstable Book for features implemented in `rustc`.

- Type System

  - `non_exhaustive` — Indicate that a type will have more fields/variants added in future.

- Debugger

  - `debugger_visualizer` — Embeds a file that specifies debugger output for a type.
  - `collapse_debuginfo` — Controls how macro invocations are encoded in debuginfo.

[attributes.testing]

# Testing attributes

The following attributes are used for specifying functions for performing tests. Compiling a crate in “test” mode enables building the test functions along with a test harness for executing the tests. Enabling the test mode also enables the `test` conditional compilation option.

[attributes.testing.test]

## The `test` attribute

[attributes.testing.test.intro]

The `test` attribute marks a function to be executed as a test.

> Example

>     #![allow(unused)]
>     fn main() {
>     pub fn add(left: u64, right: u64) -> u64 { left + right }
>     #[test]
>     fn it_works() {
>         let result = add(2, 2);
>         assert_eq!(result, 4);
>     }
>     }

[attributes.testing.test.syntax]

The `test` attribute uses the MetaWord syntax.

[attributes.testing.test.allowed-positions]

The `test` attribute may only be applied to free functions that are monomorphic, that take no arguments, and where the return type implements the `Termination` trait.

> Note

> Some of types that implement the `Termination` trait include:

> - `()`
> - `Result<T, E> where T: Termination, E: Debug`

[attributes.testing.test.duplicates]

Only the first use of `test` on a function has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[attributes.testing.test.stdlib]

The `test` attribute is exported from the standard library prelude as `std::prelude::v1::test`.

[attributes.testing.test.enabled]

These functions are only compiled when in test mode.

> Note

> The test mode is enabled by passing the `--test` argument to `rustc` or using `cargo test`.

[attributes.testing.test.success]

The test harness calls the returned value’s `report` method, and classifies the test as passed or failed depending on whether the resulting `ExitCode` represents successful termination. In particular:

- Tests that return `()` pass as long as they terminate and do not panic.
- Tests that return a `Result<(), E>` pass as long as they return `Ok(())`.
- Tests that return `ExitCode::SUCCESS` pass, and tests that return `ExitCode::FAILURE` fail.
- Tests that do not terminate neither pass nor fail.

> Example

>     #![allow(unused)]
>     fn main() {
>     use std::io;
>     fn setup_the_thing() -> io::Result<i32> { Ok(1) }
>     fn do_the_thing(s: &i32) -> io::Result<()> { Ok(()) }
>     #[test]
>     fn test_the_thing() -> io::Result<()> {
>         let state = setup_the_thing()?; // expected to succeed
>         do_the_thing(&state)?;          // expected to succeed
>         Ok(())
>     }
>     }

[attributes.testing.ignore]

## The `ignore` attribute

[attributes.testing.ignore.intro]

The `ignore` attribute can be used with the `test` attribute to tell the test harness to not execute that function as a test.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[test]
>     #[ignore]
>     fn check_thing() {
>         // …
>     }
>     }

> Note

> The `rustc` test harness supports the `--include-ignored` flag to force ignored tests to be run.

[attributes.testing.ignore.syntax]

The `ignore` attribute uses the MetaWord and MetaNameValueStr syntaxes.

[attributes.testing.ignore.reason]

The MetaNameValueStr form of the `ignore` attribute provides a way to specify a reason why the test is ignored.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[test]
>     #[ignore = "not yet implemented"]
>     fn mytest() {
>         // …
>     }
>     }

[attributes.testing.ignore.allowed-positions]

The `ignore` attribute may only be applied to functions annotated with the `test` attribute.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[attributes.testing.ignore.duplicates]

Only the first use of `ignore` on a function has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[attributes.testing.ignore.behavior]

Ignored tests are still compiled when in test mode, but they are not executed.

[attributes.testing.should_panic]

## The `should_panic` attribute

[attributes.testing.should_panic.intro]

The `should_panic` attribute causes a test to pass only if the test function to which the attribute is applied panics.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[test]
>     #[should_panic(expected = "values don't match")]
>     fn mytest() {
>         assert_eq!(1, 2, "values don't match");
>     }
>     }

[attributes.testing.should_panic.syntax]

The `should_panic` attribute has these forms:

- MetaWord

  > Example

  >     #![allow(unused)]
  >     fn main() {
  >     #[test]
  >     #[should_panic]
  >     fn mytest() { panic!("error: some message, and more"); }
  >     }

- MetaNameValueStr — The given string must appear within the panic message for the test to pass.

  > Example

  >     #![allow(unused)]
  >     fn main() {
  >     #[test]
  >     #[should_panic = "some message"]
  >     fn mytest() { panic!("error: some message, and more"); }
  >     }

- MetaListNameValueStr — As with the MetaNameValueStr syntax, the given string must appear within the panic message.

  > Example

  >     #![allow(unused)]
  >     fn main() {
  >     #[test]
  >     #[should_panic(expected = "some message")]
  >     fn mytest() { panic!("error: some message, and more"); }
  >     }

[attributes.testing.should_panic.allowed-positions]

The `should_panic` attribute may only be applied to functions annotated with the `test` attribute.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[attributes.testing.should_panic.duplicates]

Only the first use of `should_panic` on a function has effect.

> Note

> `rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.

[attributes.testing.should_panic.expected]

When the MetaNameValueStr form or the MetaListNameValueStr form with the `expected` key is used, the given string must appear somewhere within the panic message for the test to pass.

[attributes.testing.should_panic.return]

The return type of the test function must be `()`.

[attributes.derive]

# Derive

[attributes.derive.intro]

The `derive` attribute invokes one or more derive macros, allowing new items to be automatically generated for data structures. You can create `derive` macros with procedural macros.

> Example

> The `PartialEq` derive macro emits an implementation of `PartialEq` for `Foo<T> where T: PartialEq`. The `Clone` derive macro does likewise for `Clone`.

>     #![allow(unused)]
>     fn main() {
>     #[derive(PartialEq, Clone)]
>     struct Foo<T> {
>         a: i32,
>         b: T,
>     }
>     }

> The generated `impl` items are equivalent to:

>     #![allow(unused)]
>     fn main() {
>     struct Foo<T> { a: i32, b: T }
>     impl<T: PartialEq> PartialEq for Foo<T> {
>         fn eq(&self, other: &Foo<T>) -> bool {
>             self.a == other.a && self.b == other.b
>         }
>     }

>     impl<T: Clone> Clone for Foo<T> {
>         fn clone(&self) -> Self {
>             Foo { a: self.a.clone(), b: self.b.clone() }
>         }
>     }
>     }

[attributes.derive.syntax]

The `derive` attribute uses the MetaListPaths syntax to specify a list of paths to derive macros to invoke.

[attributes.derive.allowed-positions]

The `derive` attribute may only be applied to structs, enums, and unions.

[attributes.derive.duplicates]

The `derive` attribute may be used any number of times on an item. All derive macros listed in all attributes are invoked.

[attributes.derive.stdlib]

The `derive` attribute is exported in the standard library prelude as `core::prelude::v1::derive`.

[attributes.derive.built-in]

Built-in derives are defined in the language prelude. The list of built-in derives are:

- `Clone`
- `Copy`
- `Debug`
- `Default`
- `Eq`
- `Hash`
- `Ord`
- `PartialEq`
- `PartialOrd`

[attributes.derive.built-in-automatically_derived]

The built-in derives include the `automatically_derived` attribute on the implementations they generate.

[attributes.derive.behavior]

During macro expansion, for each element in the list of derives, the corresponding derive macro expands to zero or more items.

[attributes.derive.automatically_derived]

## The `automatically_derived` attribute

[attributes.derive.automatically_derived.intro]

The `automatically_derived` attribute is used to annotate an implementation to indicate that it was automatically created by a derive macro. It has no direct effect, but it may be used by tools and diagnostic lints to detect these automatically generated implementations.

> Example

> Given `#[derive(Clone)]` on `struct Example`, the derive macro may produce:

>     #![allow(unused)]
>     fn main() {
>     struct Example;
>     #[automatically_derived]
>     impl ::core::clone::Clone for Example {
>         #[inline]
>         fn clone(&self) -> Self {
>             Example
>         }
>     }
>     }

[attributes.derive.automatically_derived.syntax]

The `automatically_derived` attribute uses the MetaWord syntax.

[attributes.derive.automatically_derived.allowed-positions]

The `automatically_derived` attribute may only be applied to an implementation.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[attributes.derive.automatically_derived.duplicates]

Using `automatically_derived` more than once on an implementation has the same effect as using it once.

> Note

> `rustc` lints against any use following the first.

[attributes.derive.automatically_derived.behavior]

The `automatically_derived` attribute has no behavior.

[attributes.diagnostics]

# Diagnostic attributes

The following attributes are used for controlling or generating diagnostic messages during compilation.

[attributes.diagnostics.lint]

## Lint check attributes

A lint check names a potentially undesirable coding pattern, such as unreachable code or omitted documentation.

[attributes.diagnostics.lint.level]

The lint attributes `allow`, `expect`, `warn`, `deny`, and `forbid` use the MetaListPaths syntax to specify a list of lint names to change the lint level for the entity to which the attribute applies.

For any lint check `C`:

[attributes.diagnostics.lint.allow]

- `#[allow(C)]` overrides the check for `C` so that violations will go unreported.

[attributes.diagnostics.lint.expect]

- `#[expect(C)]` indicates that lint `C` is expected to be emitted. The attribute will suppress the emission of `C` or issue a warning, if the expectation is unfulfilled.

[attributes.diagnostics.lint.warn]

- `#[warn(C)]` warns about violations of `C` but continues compilation.

[attributes.diagnostics.lint.deny]

- `#[deny(C)]` signals an error after encountering a violation of `C`,

[attributes.diagnostics.lint.forbid]

- `#[forbid(C)]` is the same as `deny(C)`, but also forbids changing the lint level afterwards,

> Note

> The lint checks supported by `rustc` can be found via `rustc -W help`, along with their default settings and are documented in the rustc book.

    #![allow(unused)]
    fn main() {
    pub mod m1 {
        // Missing documentation is ignored here
        #[allow(missing_docs)]
        pub fn undocumented_one() -> i32 { 1 }

        // Missing documentation signals a warning here
        #[warn(missing_docs)]
        pub fn undocumented_too() -> i32 { 2 }

        // Missing documentation signals an error here
        #[deny(missing_docs)]
        pub fn undocumented_end() -> i32 { 3 }
    }
    }

[attributes.diagnostics.lint.override]

Lint attributes can override the level specified from a previous attribute, as long as the level does not attempt to change a forbidden lint (except for `deny`, which is allowed inside a `forbid` context, but ignored). Previous attributes are those from a higher level in the syntax tree, or from a previous attribute on the same entity as listed in left-to-right source order.

This example shows how one can use `allow` and `warn` to toggle a particular check on and off:

    #![allow(unused)]
    fn main() {
    #[warn(missing_docs)]
    pub mod m2 {
        #[allow(missing_docs)]
        pub mod nested {
            // Missing documentation is ignored here
            pub fn undocumented_one() -> i32 { 1 }

            // Missing documentation signals a warning here,
            // despite the allow above.
            #[warn(missing_docs)]
            pub fn undocumented_two() -> i32 { 2 }
        }

        // Missing documentation signals a warning here
        pub fn undocumented_too() -> i32 { 3 }
    }
    }

This example shows how one can use `forbid` to disallow uses of `allow` or `expect` for that lint check:

    #![allow(unused)]
    fn main() {
    #[forbid(missing_docs)]
    pub mod m3 {
        // Attempting to toggle warning signals an error here
        #[allow(missing_docs)]
        /// Returns 2.
        pub fn undocumented_too() -> i32 { 2 }
    }
    }

> Note

> `rustc` allows setting lint levels on the command-line, and also supports setting caps on the lints that are reported.

[attributes.diagnostics.lint.reason]

### Lint reasons

All lint attributes support an additional `reason` parameter, to give context why a certain attribute was added. This reason will be displayed as part of the lint message if the lint is emitted at the defined level.

    #![allow(unused)]
    fn main() {
    // `keyword_idents` is allowed by default. Here we deny it to
    // avoid migration of identifiers when we update the edition.
    #![deny(
        keyword_idents,
        reason = "we want to avoid these idents to be future compatible"
    )]

    // This name was allowed in Rust's 2015 edition. We still aim to avoid
    // this to be future compatible and not confuse end users.
    fn dyn() {}
    }

Here is another example, where the lint is allowed with a reason:

    #![allow(unused)]
    fn main() {
    use std::path::PathBuf;

    pub fn get_path() -> PathBuf {
        // The `reason` parameter on `allow` attributes acts as documentation for the reader.
        #[allow(unused_mut, reason = "this is only modified on some platforms")]
        let mut file_name = PathBuf::from("git");

        #[cfg(target_os = "windows")]
        file_name.set_extension("exe");

        file_name
    }
    }

[attributes.diagnostics.expect]

### The `#[expect]` attribute

[attributes.diagnostics.expect.intro]

The `#[expect(C)]` attribute creates a lint expectation for lint `C`. The expectation will be fulfilled, if a `#[warn(C)]` attribute at the same location would result in a lint emission. If the expectation is unfulfilled, because lint `C` would not be emitted, the `unfulfilled_lint_expectations` lint will be emitted at the attribute.

    fn main() {
        // This `#[expect]` attribute creates a lint expectation, that the `unused_variables`
        // lint would be emitted by the following statement. This expectation is
        // unfulfilled, since the `question` variable is used by the `println!` macro.
        // Therefore, the `unfulfilled_lint_expectations` lint will be emitted at the
        // attribute.
        #[expect(unused_variables)]
        let question = "who lives in a pineapple under the sea?";
        println!("{question}");

        // This `#[expect]` attribute creates a lint expectation that will be fulfilled, since
        // the `answer` variable is never used. The `unused_variables` lint, that would usually
        // be emitted, is suppressed. No warning will be issued for the statement or attribute.
        #[expect(unused_variables)]
        let answer = "SpongeBob SquarePants!";
    }

[attributes.diagnostics.expect.fulfillment]

The lint expectation is only fulfilled by lint emissions which have been suppressed by the `expect` attribute. If the lint level is modified in the scope with other level attributes like `allow` or `warn`, the lint emission will be handled accordingly and the expectation will remain unfulfilled.

    #![allow(unused)]
    fn main() {
    #[expect(unused_variables)]
    fn select_song() {
        // This will emit the `unused_variables` lint at the warn level
        // as defined by the `warn` attribute. This will not fulfill the
        // expectation above the function.
        #[warn(unused_variables)]
        let song_name = "Crab Rave";

        // The `allow` attribute suppresses the lint emission. This will not
        // fulfill the expectation as it has been suppressed by the `allow`
        // attribute and not the `expect` attribute above the function.
        #[allow(unused_variables)]
        let song_creator = "Noisestorm";

        // This `expect` attribute will suppress the `unused_variables` lint emission
        // at the variable. The `expect` attribute above the function will still not
        // be fulfilled, since this lint emission has been suppressed by the local
        // expect attribute.
        #[expect(unused_variables)]
        let song_version = "Monstercat Release";
    }
    }

[attributes.diagnostics.expect.independent]

If the `expect` attribute contains several lints, each one is expected separately. For a lint group it’s enough if one lint inside the group has been emitted:

    #![allow(unused)]
    fn main() {
    // This expectation will be fulfilled by the unused value inside the function
    // since the emitted `unused_variables` lint is inside the `unused` lint group.
    #[expect(unused)]
    pub fn thoughts() {
        let unused = "I'm running out of examples";
    }

    pub fn another_example() {
        // This attribute creates two lint expectations. The `unused_mut` lint will be
        // suppressed and with that fulfill the first expectation. The `unused_variables`
        // wouldn't be emitted, since the variable is used. That expectation will therefore
        // be unsatisfied, and a warning will be emitted.
        #[expect(unused_mut, unused_variables)]
        let mut link = "https://www.rust-lang.org/";

        println!("Welcome to our community: {link}");
    }
    }

> Note

> The behavior of `#[expect(unfulfilled_lint_expectations)]` is currently defined to always generate the `unfulfilled_lint_expectations` lint.

[attributes.diagnostics.lint.group]

### Lint groups

Lints may be organized into named groups so that the level of related lints can be adjusted together. Using a named group is equivalent to listing out the lints within that group.

    #![allow(unused)]
    fn main() {
    // This allows all lints in the "unused" group.
    #[allow(unused)]
    // This overrides the "unused_must_use" lint from the "unused"
    // group to deny.
    #[deny(unused_must_use)]
    fn example() {
        // This does not generate a warning because the "unused_variables"
        // lint is in the "unused" group.
        let x = 1;
        // This generates an error because the result is unused and
        // "unused_must_use" is marked as "deny".
        std::fs::remove_file("some_file"); // ERROR: unused `Result` that must be used
    }
    }

[attributes.diagnostics.lint.group.warnings]

There is a special group named “warnings” which includes all lints at the “warn” level. The “warnings” group ignores attribute order and applies to all lints that would otherwise warn within the entity.

    #![allow(unused)]
    fn main() {
    unsafe fn an_unsafe_fn() {}
    // The order of these two attributes does not matter.
    #[deny(warnings)]
    // The unsafe_code lint is normally "allow" by default.
    #[warn(unsafe_code)]
    fn example_err() {
        // This is an error because the `unsafe_code` warning has
        // been lifted to "deny".
        unsafe { an_unsafe_fn() } // ERROR: usage of `unsafe` block
    }
    }

[attributes.diagnostics.lint.tool]

### Tool lint attributes

[attributes.diagnostics.lint.tool.intro]

Tool lints allows using scoped lints, to `allow`, `warn`, `deny` or `forbid` lints of certain tools.

[attributes.diagnostics.lint.tool.activation]

Tool lints only get checked when the associated tool is active. If a lint attribute, such as `allow`, references a nonexistent tool lint, the compiler will not warn about the nonexistent lint until you use the tool.

Otherwise, they work just like regular lint attributes:

    // set the entire `pedantic` clippy lint group to warn
    #![warn(clippy::pedantic)]
    // silence warnings from the `filter_map` clippy lint
    #![allow(clippy::filter_map)]

    fn main() {
        // ...
    }

    // silence the `cmp_nan` clippy lint just for this function
    #[allow(clippy::cmp_nan)]
    fn foo() {
        // ...
    }

> Note

> `rustc` currently recognizes the tool lints for “clippy” and “rustdoc”.

[attributes.diagnostics.deprecated]

## The `deprecated` attribute

[attributes.diagnostics.deprecated.intro]

The `deprecated` attribute marks an item as deprecated. `rustc` will issue warnings on usage of `#[deprecated]` items. `rustdoc` will show item deprecation, including the `since` version and `note`, if available.

[attributes.diagnostics.deprecated.syntax]

The `deprecated` attribute has several forms:

- `deprecated` — Issues a generic message.
- `deprecated = "message"` — Includes the given string in the deprecation message.
- MetaListNameValueStr syntax with two optional fields:
  - `since` — Specifies a version number when the item was deprecated. `rustc` does not currently interpret the string, but external tools like Clippy may check the validity of the value.
  - `note` — Specifies a string that should be included in the deprecation message. This is typically used to provide an explanation about the deprecation and preferred alternatives.

[attributes.diagnostic.deprecated.allowed-positions]

The `deprecated` attribute may be applied to any item, trait item, enum variant, struct field, external block item, or macro definition. It cannot be applied to trait implementation items. When applied to an item containing other items, such as a module or implementation, all child items inherit the deprecation attribute.

Here is an example:

    #![allow(unused)]
    fn main() {
    #[deprecated(since = "5.2.0", note = "foo was rarely used. Users should instead use bar")]
    pub fn foo() {}

    pub fn bar() {}
    }

The RFC contains motivations and more details.

[attributes.diagnostics.must_use]

## The `must_use` attribute

[attributes.diagnostics.must_use.intro]

The `must_use` attribute is used to issue a diagnostic warning when a value is not “used”.

[attributes.diagnostics.must_use.allowed-positions]

The `must_use` attribute can be applied to user-defined composite types (`struct`s, `enum`s, and `union`s), functions, and traits.

[attributes.diagnostics.must_use.message]

The `must_use` attribute may include a message by using the MetaNameValueStr syntax such as `#[must_use = "example message"]`. The message will be given alongside the warning.

[attributes.diagnostics.must_use.type]

When used on user-defined composite types, if the expression of an expression statement has that type, then the `unused_must_use` lint is violated.

    #![allow(unused)]
    fn main() {
    #[must_use]
    struct MustUse {
        // some fields
    }

    impl MustUse {
      fn new() -> MustUse { MustUse {} }
    }

    // Violates the `unused_must_use` lint.
    MustUse::new();
    }

[attributes.diagnostics.must_use.fn]

When used on a function, if the expression of an expression statement is a call expression to that function, then the `unused_must_use` lint is violated.

    #![allow(unused)]
    fn main() {
    #[must_use]
    fn five() -> i32 { 5i32 }

    // Violates the unused_must_use lint.
    five();
    }

[attributes.diagnostics.must_use.trait]

When used on a trait declaration, a call expression of an expression statement to a function that returns an impl trait or a dyn trait of that trait violates the `unused_must_use` lint.

    #![allow(unused)]
    fn main() {
    #[must_use]
    trait Critical {}
    impl Critical for i32 {}

    fn get_critical() -> impl Critical {
        4i32
    }

    // Violates the `unused_must_use` lint.
    get_critical();
    }

[attributes.diagnostics.must_use.trait-function]

When used on a function in a trait declaration, then the behavior also applies when the call expression is a function from an implementation of the trait.

    #![allow(unused)]
    fn main() {
    trait Trait {
        #[must_use]
        fn use_me(&self) -> i32;
    }

    impl Trait for i32 {
        fn use_me(&self) -> i32 { 0i32 }
    }

    // Violates the `unused_must_use` lint.
    5i32.use_me();
    }

[attributes.diagnostics.must_use.trait-impl-function]

When used on a function in a trait implementation, the attribute does nothing.

> Note

> Trivial no-op expressions containing the value will not violate the lint. Examples include wrapping the value in a type that does not implement `Drop` and then not using that type and being the final expression of a block expression that is not used.

>     #![allow(unused)]
>     fn main() {
>     #[must_use]
>     fn five() -> i32 { 5i32 }

>     // None of these violate the unused_must_use lint.
>     (five(),);
>     Some(five());
>     { five() };
>     if true { five() } else { 0i32 };
>     match true {
>         _ => five()
>     };
>     }

> Note

> It is idiomatic to use a let statement with a pattern of `_` when a must-used value is purposely discarded.

>     #![allow(unused)]
>     fn main() {
>     #[must_use]
>     fn five() -> i32 { 5i32 }

>     // Does not violate the unused_must_use lint.
>     let _ = five();
>     }

[attributes.diagnostic.namespace]

## The `diagnostic` tool attribute namespace

[attributes.diagnostic.namespace.intro]

The `#[diagnostic]` attribute namespace is a home for attributes to influence compile-time error messages. The hints provided by these attributes are not guaranteed to be used.

[attributes.diagnostic.namespace.unknown-invalid-syntax]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/deny_malformed_attribute.rs
- tests/ui/diagnostic_namespace/non_existing_attributes_accepted.rs
- tests/ui/diagnostic_namespace/suggest_typos.rs

Unknown attributes in this namespace are accepted, though they may emit warnings for unused attributes. Additionally, invalid inputs to known attributes will typically be a warning (see the attribute definitions for details). This is meant to allow adding or discarding attributes and changing inputs in the future to allow changes without the need to keep the non-meaningful attributes or options working.

[attributes.diagnostic.on_unimplemented]

### The `diagnostic::on_unimplemented` attribute

[attributes.diagnostic.on_unimplemented.intro]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/custom-on-unimplemented-diagnostic.rs
- tests/ui/diagnostic_namespace/on_unimplemented/error_is_shown_in_downstream_crates.rs
- tests/ui/diagnostic_namespace/on_unimplemented/on_unimplemented_simple.rs
- tests/ui/traits/negative-bounds/on-unimplemented.rs

The `#[diagnostic::on_unimplemented]` attribute is a hint to the compiler to supplement the error message that would normally be generated in scenarios where a trait is required but not implemented on a type.

[attributes.diagnostic.on_unimplemented.allowed-positions]

The attribute should be placed on a trait declaration, though it is not an error to be located in other positions.

[attributes.diagnostic.on_unimplemented.syntax]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/malformed_foreign_on_unimplemented.rs
- tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.rs
- tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.rs
- tests/ui/diagnostic_namespace/on_unimplemented/ignore_unsupported_options_and_continue_to_use_fallback.rs

The attribute uses the MetaListNameValueStr syntax to specify its inputs, though any malformed input to the attribute is not considered as an error to provide both forwards and backwards compatibility.

[attributes.diagnostic.on_unimplemented.keys]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/custom-on-unimplemented-diagnostic.rs
- tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.rs
- tests/ui/diagnostic_namespace/on_unimplemented/on_unimplemented_simple.rs

The following keys have the given meaning:

- `message` — The text for the top level error message.
- `label` — The text for the label shown inline in the broken code in the error message.
- `note` — Provides additional notes.

[attributes.diagnostic.on_unimplemented.note-repetition]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/multiple_notes.rs

The `note` option can appear several times, which results in several note messages being emitted.

[attributes.diagnostic.on_unimplemented.repetition]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/ignore_unsupported_options_and_continue_to_use_fallback.rs
- tests/ui/diagnostic_namespace/on_unimplemented/report_warning_on_duplicated_options.rs

If any of the other options appears several times the first occurrence of the relevant option specifies the actually used value. Subsequent occurrences generates a warning.

[attributes.diagnostic.on_unimplemented.unknown-keys]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/do_not_fail_parsing_on_invalid_options_1.rs

A warning is generated for any unknown keys.

[attributes.diagnostic.on_unimplemented.format-string]

All three options accept a string as an argument, interpreted using the same formatting as a `std::fmt` string.

[attributes.diagnostic.on_unimplemented.format-parameters]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.rs

Format parameters with the given named parameter will be replaced with the following text:

- `{Self}` — The name of the type implementing the trait.
- `{` GenericParameterName `}` — The name of the generic argument’s type for the given generic parameter.

[attributes.diagnostic.on_unimplemented.invalid-formats]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/do_not_accept_options_of_the_internal_rustc_attribute.rs

Any other format parameter will generate a warning, but will otherwise be included in the string as-is.

[attributes.diagnostic.on_unimplemented.invalid-string]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/on_unimplemented/broken_format.rs

Invalid format strings may generate a warning, but are otherwise allowed, but may not display as intended. Format specifiers may generate a warning, but are otherwise ignored.

In this example:

    #[diagnostic::on_unimplemented(
        message = "My Message for `ImportantTrait<{A}>` implemented for `{Self}`",
        label = "My Label",
        note = "Note 1",
        note = "Note 2"
    )]
    trait ImportantTrait<A> {}

    fn use_my_trait(_: impl ImportantTrait<i32>) {}

    fn main() {
        use_my_trait(String::new());
    }

the compiler may generate an error message which looks like this:

    error[E0277]: My Message for `ImportantTrait<i32>` implemented for `String`
      --> src/main.rs:14:18
       |
    14 |     use_my_trait(String::new());
       |     ------------ ^^^^^^^^^^^^^ My Label
       |     |
       |     required by a bound introduced by this call
       |
       = help: the trait `ImportantTrait<i32>` is not implemented for `String`
       = note: Note 1
       = note: Note 2

[attributes.diagnostic.do_not_recommend]

### The `diagnostic::do_not_recommend` attribute

[attributes.diagnostic.do_not_recommend.intro]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/do_not_recommend/as_expression.rs
- tests/ui/diagnostic_namespace/do_not_recommend/nested.rs
- tests/ui/diagnostic_namespace/do_not_recommend/simple.rs
- tests/ui/diagnostic_namespace/do_not_recommend/stacked.rs
- tests/ui/diagnostic_namespace/do_not_recommend/supress_suggestions_in_help.rs
- tests/ui/diagnostic_namespace/do_not_recommend/type_mismatch.rs
- tests/ui/diagnostic_namespace/do_not_recommend/with_lifetime.rs

The `#[diagnostic::do_not_recommend]` attribute is a hint to the compiler to not show the annotated trait implementation as part of a diagnostic message.

> Note

> Suppressing the recommendation can be useful if you know that the recommendation would normally not be useful to the programmer. This often occurs with broad, blanket impls. The recommendation may send the programmer down the wrong path, or the trait implementation may be an internal detail that you don’t want to expose, or the bounds may not be able to be satisfied by the programmer.

> For example, in an error message about a type not implementing a required trait, the compiler may find a trait implementation that would satisfy the requirements if it weren’t for specific bounds in the trait implementation. The compiler may tell the user that there is an impl, but the problem is the bounds in the trait implementation. The `#[diagnostic::do_not_recommend]` attribute can be used to tell the compiler to not tell the user about the trait implementation, and instead simply tell the user the type doesn’t implement the required trait.

[attributes.diagnostic.do_not_recommend.allowed-positions]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/do_not_recommend/incorrect-locations.rs

The attribute should be placed on a trait implementation item, though it is not an error to be located in other positions.

[attributes.diagnostic.do_not_recommend.syntax]
Tests
Tests with this rule:

- tests/ui/diagnostic_namespace/do_not_recommend/does_not_acccept_args.rs

The attribute does not accept any arguments, though unexpected arguments are not considered as an error.

In the following example, there is a trait called `AsExpression` which is used for casting arbitrary types to the `Expression` type used in an SQL library. There is a method called `check` which takes an `AsExpression`.

    pub trait Expression {
        type SqlType;
    }

    pub trait AsExpression<ST> {
        type Expression: Expression<SqlType = ST>;
    }

    pub struct Text;
    pub struct Integer;

    pub struct Bound<T>(T);
    pub struct SelectInt;

    impl Expression for SelectInt {
        type SqlType = Integer;
    }

    impl<T> Expression for Bound<T> {
        type SqlType = T;
    }

    impl AsExpression<Integer> for i32 {
        type Expression = Bound<Integer>;
    }

    impl AsExpression<Text> for &'_ str {
        type Expression = Bound<Text>;
    }

    impl<T> Foo for T where T: Expression {}

    // Uncomment this line to change the recommendation.
    // #[diagnostic::do_not_recommend]
    impl<T, ST> AsExpression<ST> for T
    where
        T: Expression<SqlType = ST>,
    {
        type Expression = T;
    }

    trait Foo: Expression + Sized {
        fn check<T>(&self, _: T) -> <T as AsExpression<<Self as Expression>::SqlType>>::Expression
        where
            T: AsExpression<Self::SqlType>,
        {
            todo!()
        }
    }

    fn main() {
        SelectInt.check("bar");
    }

The `SelectInt` type’s `check` method is expecting an `Integer` type. Calling it with an i32 type works, as it gets converted to an `Integer` by the `AsExpression` trait. However, calling it with a string does not, and generates a an error that may look like this:

    error[E0277]: the trait bound `&str: Expression` is not satisfied
      --> src/main.rs:53:15
       |
    53 |     SelectInt.check("bar");
       |               ^^^^^ the trait `Expression` is not implemented for `&str`
       |
       = help: the following other types implement trait `Expression`:
                 Bound<T>
                 SelectInt
    note: required for `&str` to implement `AsExpression<Integer>`
      --> src/main.rs:45:13
       |
    45 | impl<T, ST> AsExpression<ST> for T
       |             ^^^^^^^^^^^^^^^^     ^
    46 | where
    47 |     T: Expression<SqlType = ST>,
       |        ------------------------ unsatisfied trait bound introduced here

By adding the `#[diagnostic::do_not_recommend]` attribute to the blanket `impl` for `AsExpression`, the message changes to:

    error[E0277]: the trait bound `&str: AsExpression<Integer>` is not satisfied
      --> src/main.rs:53:15
       |
    53 |     SelectInt.check("bar");
       |               ^^^^^ the trait `AsExpression<Integer>` is not implemented for `&str`
       |
       = help: the trait `AsExpression<Integer>` is not implemented for `&str`
               but trait `AsExpression<Text>` is implemented for it
       = help: for that trait implementation, expected `Text`, found `Integer`

The first error message includes a somewhat confusing error message about the relationship of `&str` and `Expression`, as well as the unsatisfied trait bound in the blanket impl. After adding `#[diagnostic::do_not_recommend]`, it no longer considers the blanket impl for the recommendation. The message should be a little clearer, with an indication that a string cannot be converted to an `Integer`.

[attributes.codegen]

# Code generation attributes

The following attributes are used for controlling code generation.

[attributes.codegen.inline]

### The `inline` attribute

[attributes.codegen.inline.intro]

The `inline` attribute suggests whether a copy of the attributed function’s code should be placed in the caller rather than generating a call to the function.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[inline]
>     pub fn example1() {}

>     #[inline(always)]
>     pub fn example2() {}

>     #[inline(never)]
>     pub fn example3() {}
>     }

> Note

> `rustc` automatically inlines functions when doing so seems worthwhile. Use this attribute carefully as poor decisions about what to inline can slow down programs.

[attributes.codegen.inline.syntax]

The syntax for the `inline` attribute is:

Syntax
InlineAttribute →
inline ( always )
| inline ( never )
| inline

[attributes.codegen.inline.allowed-positions]

The `inline` attribute may only be applied to functions with bodies — closures, async blocks, free functions, associated functions in an inherent impl or trait impl, and associated functions in a trait definition when those functions have a default definition .

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

> Note

> Though the attribute can be applied to closures and async blocks, the usefulness of this is limited as we do not yet support attributes on expressions.

>     #![allow(unused)]
>     fn main() {
>     // We allow attributes on statements.
>     #[inline] || (); // OK
>     #[inline] async {}; // OK
>     }

>     #![allow(unused)]
>     fn main() {
>     // We don't yet allow attributes on expressions.
>     let f = #[inline] || (); // ERROR
>     }

[attributes.codegen.inline.duplicates]

Only the first use of `inline` on a function has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[attributes.codegen.inline.modes]

The `inline` attribute supports these modes:

- `#[inline]` suggests performing inline expansion.
- `#[inline(always)]` suggests that inline expansion should always be performed.
- `#[inline(never)]` suggests that inline expansion should never be performed.

> Note

> In every form the attribute is a hint. The compiler may ignore it.

[attributes.codegen.inline.trait]

When `inline` is applied to a function in a trait, it applies only to the code of the default definition.

[attributes.codegen.inline.async]

When `inline` is applied to an async function or async closure, it applies only to the code of the generated `poll` function.

> Note

> For more details, see Rust issue #129347.

[attributes.codegen.inline.externally-exported]

The `inline` attribute is ignored if the function is externally exported with `no_mangle` or `export_name`.

[attributes.codegen.cold]

### The `cold` attribute

[attributes.codegen.cold.intro]
Tests
Tests with this rule:

- tests/codegen-llvm/cold-attribute.rs

The `cold` attribute suggests that the attributed function is unlikely to be called which may help the compiler produce better code.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[cold]
>     pub fn example() {}
>     }

[attributes.codegen.cold.syntax]

The `cold` attribute uses the MetaWord syntax.

[attributes.codegen.cold.allowed-positions]

The `cold` attribute may only be applied to functions with bodies — closures, async blocks, free functions, associated functions in an inherent impl or trait impl, and associated functions in a trait definition when those functions have a default definition .

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

> Note

> Though the attribute can be applied to closures and async blocks, the usefulness of this is limited as we do not yet support attributes on expressions.

[attributes.codegen.cold.duplicates]

Only the first use of `cold` on a function has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[attributes.codegen.cold.trait]
Tests
Tests with this rule:

- tests/codegen-llvm/cold-attribute.rs

When `cold` is applied to a function in a trait, it applies only to the code of the default definition.

[attributes.codegen.naked]

## The `naked` attribute

[attributes.codegen.naked.intro]

The `naked` attribute prevents the compiler from emitting a function prologue and epilogue for the attributed function.

[attributes.codegen.naked.body]

The function body must consist of exactly one `naked_asm!` macro invocation.

[attributes.codegen.naked.prologue-epilogue]

No function prologue or epilogue is generated for the attributed function. The assembly code in the `naked_asm!` block constitutes the full body of a naked function.

[attributes.codegen.naked.unsafe-attribute]

The `naked` attribute is an unsafe attribute. Annotating a function with `#[unsafe(naked)]` comes with the safety obligation that the body must respect the function’s calling convention, uphold its signature, and either return or diverge (i.e., not fall through past the end of the assembly code).

[attributes.codegen.naked.call-stack]

The assembly code may assume that the call stack and register state are valid on entry as per the signature and calling convention of the function.

[attributes.codegen.naked.no-duplication]

The assembly code may not be duplicated by the compiler except when monomorphizing polymorphic functions.

> Note

> Guaranteeing when the assembly code may or may not be duplicated is important for naked functions that define symbols.

[attributes.codegen.naked.unused-variables]

The `unused_variables` lint is suppressed within naked functions.

[attributes.codegen.naked.inline]

The `inline` attribute cannot by applied to a naked function.

[attributes.codegen.naked.track_caller]

The `track_caller` attribute cannot be applied to a naked function.

[attributes.codegen.naked.testing]

The testing attributes cannot be applied to a naked function.

[attributes.codegen.no_builtins]

## The `no_builtins` attribute

[attributes.codegen.no_builtins.intro]

The `no_builtins` attribute disables optimization of certain code patterns related to calls to library functions that are assumed to exist.

> Example

>     #![allow(unused)]
>     #![no_builtins]
>     fn main() {
>     }

[attributes.codegen.no_builtins.syntax]

The `no_builtins` attribute uses the MetaWord syntax.

[attributes.codegen.no_builtins.allowed-positions]

The `no_builtins` attribute can only be applied to the crate root.

[attributes.codegen.no_builtins.duplicates]

Only the first use of the `no_builtins` attribute has effect.

> Note

> `rustc` lints against any use following the first.

[attributes.codegen.target_feature]

## The `target_feature` attribute

[attributes.codegen.target_feature.intro]

The `target_feature` attribute may be applied to a function to enable code generation of that function for specific platform architecture features. It uses the MetaListNameValueStr syntax with a single key of `enable` whose value is a string of comma-separated feature names to enable.

    #![allow(unused)]
    fn main() {
    #[cfg(target_feature = "avx2")]
    #[target_feature(enable = "avx2")]
    fn foo_avx2() {}
    }

[attributes.codegen.target_feature.arch]

Each target architecture has a set of features that may be enabled. It is an error to specify a feature for a target architecture that the crate is not being compiled for.

[attributes.codegen.target_feature.closures]

Closures defined within a `target_feature`-annotated function inherit the attribute from the enclosing function.

[attributes.codegen.target_feature.target-ub]

It is undefined behavior to call a function that is compiled with a feature that is not supported on the current platform the code is running on, except if the platform explicitly documents this to be safe.

[attributes.codegen.target_feature.safety-restrictions]

The following restrictions apply unless otherwise specified by the platform rules below:

- Safe `#[target_feature]` functions (and closures that inherit the attribute) can only be safely called within a caller that enables all the `target_feature`s that the callee enables. This restriction does not apply in an `unsafe` context.
- Safe `#[target_feature]` functions (and closures that inherit the attribute) can only be coerced to safe function pointers in contexts that enable all the `target_feature`s that the coercee enables. This restriction does not apply to `unsafe` function pointers.

Implicitly enabled features are included in this rule. For example an `sse2` function can call ones marked with `sse`.

    #![allow(unused)]
    fn main() {
    #[cfg(target_feature = "sse2")] {
    #[target_feature(enable = "sse")]
    fn foo_sse() {}

    fn bar() {
        // Calling `foo_sse` here is unsafe, as we must ensure that SSE is
        // available first, even if `sse` is enabled by default on the target
        // platform or manually enabled as compiler flags.
        unsafe {
            foo_sse();
        }
    }

    #[target_feature(enable = "sse")]
    fn bar_sse() {
        // Calling `foo_sse` here is safe.
        foo_sse();
        || foo_sse();
    }

    #[target_feature(enable = "sse2")]
    fn bar_sse2() {
        // Calling `foo_sse` here is safe because `sse2` implies `sse`.
        foo_sse();
    }
    }
    }

[attributes.codegen.target_feature.fn-traits]

A function with a `#[target_feature]` attribute never implements the `Fn` family of traits, although closures inheriting features from the enclosing function do.

[attributes.codegen.target_feature.allowed-positions]

The `#[target_feature]` attribute is not allowed on the following places:

- the `main` function
- a `panic_handler` function
- safe trait methods
- safe default functions in traits

[attributes.codegen.target_feature.inline]

Functions marked with `target_feature` are not inlined into a context that does not support the given features. The `#[inline(always)]` attribute may not be used with a `target_feature` attribute.

[attributes.codegen.target_feature.availability]

### Available features

The following is a list of the available feature names.

[attributes.codegen.target_feature.x86]

#### `x86` or `x86_64`

Executing code with unsupported features is undefined behavior on this platform. Hence on this platform usage of `#[target_feature]` functions follows the above restrictions.

Feature | Implicitly Enables | Description
--- | --- | ---
`adx` |  | ADX — Multi-Precision Add-Carry Instruction Extensions
`aes` | `sse2` | AES — Advanced Encryption Standard
`avx` | `sse4.2` | AVX — Advanced Vector Extensions
`avx2` | `avx` | AVX2 — Advanced Vector Extensions 2
`avx512bf16` | `avx512bw` | AVX512-BF16 — Advanced Vector Extensions 512-bit - Bfloat16 Extensions
`avx512bitalg` | `avx512bw` | AVX512-BITALG — Advanced Vector Extensions 512-bit - Bit Algorithms
`avx512bw` | `avx512f` | AVX512-BW — Advanced Vector Extensions 512-bit - Byte and Word Instructions
`avx512cd` | `avx512f` | AVX512-CD — Advanced Vector Extensions 512-bit - Conflict Detection Instructions
`avx512dq` | `avx512f` | AVX512-DQ — Advanced Vector Extensions 512-bit - Doubleword and Quadword Instructions
`avx512f` | `avx2`, `fma`, `f16c` | AVX512-F — Advanced Vector Extensions 512-bit - Foundation
`avx512fp16` | `avx512bw` | AVX512-FP16 — Advanced Vector Extensions 512-bit - Float16 Extensions
`avx512ifma` | `avx512f` | AVX512-IFMA — Advanced Vector Extensions 512-bit - Integer Fused Multiply Add
`avx512vbmi` | `avx512bw` | AVX512-VBMI — Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions
`avx512vbmi2` | `avx512bw` | AVX512-VBMI2 — Advanced Vector Extensions 512-bit - Vector Byte Manipulation Instructions 2
`avx512vl` | `avx512f` | AVX512-VL — Advanced Vector Extensions 512-bit - Vector Length Extensions
`avx512vnni` | `avx512f` | AVX512-VNNI — Advanced Vector Extensions 512-bit - Vector Neural Network Instructions
`avx512vp2intersect` | `avx512f` | AVX512-VP2INTERSECT — Advanced Vector Extensions 512-bit - Vector Pair Intersection to a Pair of Mask Registers
`avx512vpopcntdq` | `avx512f` | AVX512-VPOPCNTDQ — Advanced Vector Extensions 512-bit - Vector Population Count Instruction
`avxifma` | `avx2` | AVX-IFMA — Advanced Vector Extensions - Integer Fused Multiply Add
`avxneconvert` | `avx2` | AVX-NE-CONVERT — Advanced Vector Extensions - No-Exception Floating-Point conversion Instructions
`avxvnni` | `avx2` | AVX-VNNI — Advanced Vector Extensions - Vector Neural Network Instructions
`avxvnniint16` | `avx2` | AVX-VNNI-INT16 — Advanced Vector Extensions - Vector Neural Network Instructions with 16-bit Integers
`avxvnniint8` | `avx2` | AVX-VNNI-INT8 — Advanced Vector Extensions - Vector Neural Network Instructions with 8-bit Integers
`bmi1` |  | BMI1 — Bit Manipulation Instruction Sets
`bmi2` |  | BMI2 — Bit Manipulation Instruction Sets 2
`cmpxchg16b` |  | `cmpxchg16b` — Compares and exchange 16 bytes (128 bits) of data atomically
`f16c` | `avx` | F16C — 16-bit floating point conversion instructions
`fma` | `avx` | FMA3 — Three-operand fused multiply-add
`fxsr` |  | `fxsave` and `fxrstor` — Save and restore x87 FPU, MMX Technology, and SSE State
`gfni` | `sse2` | GFNI — Galois Field New Instructions
`kl` | `sse2` | KEYLOCKER — Intel Key Locker Instructions
`lzcnt` |  | `lzcnt` — Leading zeros count
`movbe` |  | `movbe` — Move data after swapping bytes
`pclmulqdq` | `sse2` | `pclmulqdq` — Packed carry-less multiplication quadword
`popcnt` |  | `popcnt` — Count of bits set to 1
`rdrand` |  | `rdrand` — Read random number
`rdseed` |  | `rdseed` — Read random seed
`sha` | `sse2` | SHA — Secure Hash Algorithm
`sha512` | `avx2` | SHA512 — Secure Hash Algorithm with 512-bit digest
`sm3` | `avx` | SM3 — ShangMi 3 Hash Algorithm
`sm4` | `avx2` | SM4 — ShangMi 4 Cipher Algorithm
`sse` |  | SSE — Streaming SIMD Extensions
`sse2` | `sse` | SSE2 — Streaming SIMD Extensions 2
`sse3` | `sse2` | SSE3 — Streaming SIMD Extensions 3
`sse4.1` | `ssse3` | SSE4.1 — Streaming SIMD Extensions 4.1
`sse4.2` | `sse4.1` | SSE4.2 — Streaming SIMD Extensions 4.2
`sse4a` | `sse3` | SSE4a — Streaming SIMD Extensions 4a
`ssse3` | `sse3` | SSSE3 — Supplemental Streaming SIMD Extensions 3
`tbm` |  | TBM — Trailing Bit Manipulation
`vaes` | `avx2`, `aes` | VAES — Vector AES Instructions
`vpclmulqdq` | `avx`, `pclmulqdq` | VPCLMULQDQ — Vector Carry-less multiplication of Quadwords
`widekl` | `kl` | KEYLOCKER_WIDE — Intel Wide Keylocker Instructions
`xsave` |  | `xsave` — Save processor extended states
`xsavec` |  | `xsavec` — Save processor extended states with compaction
`xsaveopt` |  | `xsaveopt` — Save processor extended states optimized
`xsaves` |  | `xsaves` — Save processor extended states supervisor

[attributes.codegen.target_feature.aarch64]

#### `aarch64`

On this platform the usage of `#[target_feature]` functions follows the above restrictions.

Further documentation on these features can be found in the ARM Architecture Reference Manual, or elsewhere on developer.arm.com.

> Note

> The following pairs of features should both be marked as enabled or disabled together if used:

> - `paca` and `pacg`, which LLVM currently implements as one feature.

Feature | Implicitly Enables | Feature Name
--- | --- | ---
`aes` | `neon` | FEAT_AES & FEAT_PMULL — Advanced SIMD AES & PMULL instructions
`bf16` |  | FEAT_BF16 — BFloat16 instructions
`bti` |  | FEAT_BTI — Branch Target Identification
`crc` |  | FEAT_CRC — CRC32 checksum instructions
`dit` |  | FEAT_DIT — Data Independent Timing instructions
`dotprod` | `neon` | FEAT_DotProd — Advanced SIMD Int8 dot product instructions
`dpb` |  | FEAT_DPB — Data cache clean to point of persistence
`dpb2` | `dpb` | FEAT_DPB2 — Data cache clean to point of deep persistence
`f32mm` | `sve` | FEAT_F32MM — SVE single-precision FP matrix multiply instruction
`f64mm` | `sve` | FEAT_F64MM — SVE double-precision FP matrix multiply instruction
`fcma` | `neon` | FEAT_FCMA — Floating point complex number support
`fhm` | `fp16` | FEAT_FHM — Half-precision FP FMLAL instructions
`flagm` |  | FEAT_FLAGM — Conditional flag manipulation
`fp16` | `neon` | FEAT_FP16 — Half-precision FP data processing
`frintts` |  | FEAT_FRINTTS — Floating-point to int helper instructions
`i8mm` |  | FEAT_I8MM — Int8 Matrix Multiplication
`jsconv` | `neon` | FEAT_JSCVT — JavaScript conversion instruction
`lor` |  | FEAT_LOR — Limited Ordering Regions extension
`lse` |  | FEAT_LSE — Large System Extensions
`mte` |  | FEAT_MTE & FEAT_MTE2 — Memory Tagging Extension
`neon` |  | FEAT_AdvSimd & FEAT_FP — Floating Point and Advanced SIMD extension
`paca` |  | FEAT_PAUTH — Pointer Authentication (address authentication)
`pacg` |  | FEAT_PAUTH — Pointer Authentication (generic authentication)
`pan` |  | FEAT_PAN — Privileged Access-Never extension
`pmuv3` |  | FEAT_PMUv3 — Performance Monitors extension (v3)
`rand` |  | FEAT_RNG — Random Number Generator
`ras` |  | FEAT_RAS & FEAT_RASv1p1 — Reliability, Availability and Serviceability extension
`rcpc` |  | FEAT_LRCPC — Release consistent Processor Consistent
`rcpc2` | `rcpc` | FEAT_LRCPC2 — RcPc with immediate offsets
`rdm` | `neon` | FEAT_RDM — Rounding Double Multiply accumulate
`sb` |  | FEAT_SB — Speculation Barrier
`sha2` | `neon` | FEAT_SHA1 & FEAT_SHA256 — Advanced SIMD SHA instructions
`sha3` | `sha2` | FEAT_SHA512 & FEAT_SHA3 — Advanced SIMD SHA instructions
`sm4` | `neon` | FEAT_SM3 & FEAT_SM4 — Advanced SIMD SM3/4 instructions
`spe` |  | FEAT_SPE — Statistical Profiling Extension
`ssbs` |  | FEAT_SSBS & FEAT_SSBS2 — Speculative Store Bypass Safe
`sve` | `neon` | FEAT_SVE — Scalable Vector Extension
`sve2` | `sve` | FEAT_SVE2 — Scalable Vector Extension 2
`sve2-aes` | `sve2`, `aes` | FEAT_SVE_AES & FEAT_SVE_PMULL128 — SVE AES instructions
`sve2-bitperm` | `sve2` | FEAT_SVE2_BitPerm — SVE Bit Permute
`sve2-sha3` | `sve2`, `sha3` | FEAT_SVE2_SHA3 — SVE SHA3 instructions
`sve2-sm4` | `sve2`, `sm4` | FEAT_SVE2_SM4 — SVE SM4 instructions
`tme` |  | FEAT_TME — Transactional Memory Extension
`vh` |  | FEAT_VHE — Virtualization Host Extensions

[attributes.codegen.target_feature.loongarch]

#### `loongarch`

On this platform the usage of `#[target_feature]` functions follows the above restrictions.

Feature | Implicitly Enables | Description
--- | --- | ---
`f` |  | F — Single-precision float-point instructions
`d` | `f` | D — Double-precision float-point instructions
`frecipe` |  | FRECIPE — Reciprocal approximation instructions
`lasx` | `lsx` | LASX — 256-bit vector instructions
`lbt` |  | LBT — Binary translation instructions
`lsx` | `d` | LSX — 128-bit vector instructions
`lvz` |  | LVZ — Virtualization instructions

[attributes.codegen.target_feature.riscv]

#### `riscv32` or `riscv64`

On this platform the usage of `#[target_feature]` functions follows the above restrictions.

Further documentation on these features can be found in their respective specification. Many specifications are described in the RISC-V ISA Manual, version 20250508, or in another manual hosted on the RISC-V GitHub Account.

Feature | Implicitly Enables | Description
--- | --- | ---
`a` | `zaamo`, `zalrsc` | A — Atomic instructions
`b` | `zba`, `zbc`, `zbs` | B — Bit Manipulation instructions
`c` | `zca` | C — Compressed instructions
`m` |  | M — Integer Multiplication and Division instructions
`za64rs` | `za128rs` | Za64rs — Platform Behavior: Naturally aligned Reservation sets with ≦ 64 Bytes
`za128rs` |  | Za128rs — Platform Behavior: Naturally aligned Reservation sets with ≦ 128 Bytes
`zaamo` |  | Zaamo — Atomic Memory Operation instructions
`zabha` | `zaamo` | Zabha — Byte and Halfword Atomic Memory Operation instructions
`zacas` | `zaamo` | Zacas — Atomic Compare-and-Swap (CAS) instructions
`zalrsc` |  | Zalrsc — Load-Reserved/Store-Conditional instructions
`zama16b` |  | Zama16b — Platform Behavior: Misaligned loads, stores, and AMOs to main memory regions that do not cross a naturally aligned 16-byte boundary are atomic
`zawrs` |  | Zawrs — Wait-on-Reservation-Set instructions
`zba` |  | Zba — Address Generation instructions
`zbb` |  | Zbb — Basic bit-manipulation
`zbc` | `zbkc` | Zbc — Carry-less multiplication
`zbkb` |  | Zbkb — Bit Manipulation Instructions for Cryptography
`zbkc` |  | Zbkc — Carry-less multiplication for Cryptography
`zbkx` |  | Zbkx — Crossbar permutations
`zbs` |  | Zbs — Single-bit instructions
`zca` |  | Zca — Compressed instructions: integer part subset
`zcb` | `zca` | Zcb — Simple Code-size Saving Compressed instructions
`zcmop` | `zca` | Zcmop — Compressed May-Be-Operations
`zic64b` |  | Zic64b — Platform Behavior: Naturally aligned 64 byte Cache blocks
`zicbom` |  | Zicbom — Cache-Block Management instructions
`zicbop` |  | Zicbop — Cache-Block Prefetch Hint instructions
`zicboz` |  | Zicboz — Cache-Block Zero instruction
`ziccamoa` |  | Ziccamoa — Platform Behavior: Cacheable and Coherent Main memory supports all basic atomic operations
`ziccif` |  | Ziccif — Platform Behavior: Cacheable and Coherent Main memory supports instruction fetch and fetches of naturally aligned power-of-2 sizes up to `min(ILEN,XLEN)` are atomic
`zicclsm` |  | Zicclsm — Platform Behavior: Cacheable and Coherent Main memory supports misaligned load/store accesses
`ziccrse` |  | Ziccrse — Platform Behavior: Cacheable and Coherent Main memory guarantees eventual success on LR/SC sequences
`zicntr` | `zicsr` | Zicntr — Base Counters and Timers
`zicond` |  | Zicond — Integer Conditional Operation instructions
`zicsr` |  | Zicsr — Control and Status Register (CSR) instructions
`zifencei` |  | Zifencei — Instruction-Fetch Fence instruction
`zihintntl` |  | Zihintntl — Non-Temporal Locality Hint instructions
`zihintpause` |  | Zihintpause — Pause Hint instruction
`zihpm` | `zicsr` | Zihpm — Hardware Performance Counters
`zimop` |  | Zimop — May-Be-Operations
`zk` | `zkn`, `zkr`, `zks`, `zkt`, `zbkb`, `zbkc`, `zkbx` | Zk — Scalar Cryptography
`zkn` | `zknd`, `zkne`, `zknh`, `zbkb`, `zbkc`, `zkbx` | Zkn — NIST Algorithm suite extension
`zknd` |  | Zknd — NIST Suite: AES Decryption
`zkne` |  | Zkne — NIST Suite: AES Encryption
`zknh` |  | Zknh — NIST Suite: Hash Function Instructions
`zkr` |  | Zkr — Entropy Source Extension
`zks` | `zksed`, `zksh`, `zbkb`, `zbkc`, `zkbx` | Zks — ShangMi Algorithm Suite
`zksed` |  | Zksed — ShangMi Suite: SM4 Block Cipher Instructions
`zksh` |  | Zksh — ShangMi Suite: SM3 Hash Function Instructions
`zkt` |  | Zkt — Data Independent Execution Latency Subset
`ztso` |  | Ztso — Total Store Ordering

[attributes.codegen.target_feature.wasm]

#### `wasm32` or `wasm64`

Safe `#[target_feature]` functions may always be used in safe contexts on Wasm platforms. It is impossible to cause undefined behavior via the `#[target_feature]` attribute because attempting to use instructions unsupported by the Wasm engine will fail at load time without the risk of being interpreted in a way different from what the compiler expected.

Feature | Implicitly Enables | Description
--- | --- | ---
`bulk-memory` |  | WebAssembly bulk memory operations proposal
`extended-const` |  | WebAssembly extended const expressions proposal
`mutable-globals` |  | WebAssembly mutable global proposal
`nontrapping-fptoint` |  | WebAssembly non-trapping float-to-int conversion proposal
`relaxed-simd` | `simd128` | WebAssembly relaxed simd proposal
`sign-ext` |  | WebAssembly sign extension operators Proposal
`simd128` |  | WebAssembly simd proposal
`multivalue` |  | WebAssembly multivalue proposal
`reference-types` |  | WebAssembly reference-types proposal
`tail-call` |  | WebAssembly tail-call proposal

[attributes.codegen.target_feature.s390x]

#### `s390x`

On `s390x` targets, use of functions with the `#[target_feature]` attribute follows the above restrictions.

Further documentation on these features can be found in the “Additions to z/Architecture” section of Chapter 1 of the z/Architecture Principles of Operation.

Feature | Implicitly Enables | Description
--- | --- | ---
`vector` |  | 128-bit vector instructions
`vector-enhancements-1` | `vector` | vector enhancements 1
`vector-enhancements-2` | `vector-enhancements-1` | vector enhancements 2
`vector-enhancements-3` | `vector-enhancements-2` | vector enhancements 3
`vector-packed-decimal` | `vector` | vector packed-decimal
`vector-packed-decimal-enhancement` | `vector-packed-decimal` | vector packed-decimal enhancement
`vector-packed-decimal-enhancement-2` | `vector-packed-decimal-enhancement-2` | vector packed-decimal enhancement 2
`vector-packed-decimal-enhancement-3` | `vector-packed-decimal-enhancement-3` | vector packed-decimal enhancement 3
`nnp-assist` | `vector` | nnp assist
`miscellaneous-extensions-2` |  | miscellaneous extensions 2
`miscellaneous-extensions-3` |  | miscellaneous extensions 3
`miscellaneous-extensions-4` |  | miscellaneous extensions 4

[attributes.codegen.target_feature.info]

### Additional information

[attributes.codegen.target_feature.remark-cfg]

See the `target_feature` conditional compilation option for selectively enabling or disabling compilation of code based on compile-time settings. Note that this option is not affected by the `target_feature` attribute, and is only driven by the features enabled for the entire crate.

[attributes.codegen.target_feature.remark-rt]

Whether a feature is enabled can be checked at runtime using a platform-specific macro from the standard library, for instance `is_x86_feature_detected` or `is_aarch64_feature_detected`.

> Note

> `rustc` has a default set of features enabled for each target and CPU. The CPU may be chosen with the `-C target-cpu` flag. Individual features may be enabled or disabled for an entire crate with the `-C target-feature` flag.

[attributes.codegen.track_caller]

## The `track_caller` attribute

[attributes.codegen.track_caller.allowed-positions]

The `track_caller` attribute may be applied to any function with `"Rust"` ABI with the exception of the entry point `fn main`.

[attributes.codegen.track_caller.traits]

When applied to functions and methods in trait declarations, the attribute applies to all implementations. If the trait provides a default implementation with the attribute, then the attribute also applies to override implementations.

[attributes.codegen.track_caller.extern]

When applied to a function in an `extern` block the attribute must also be applied to any linked implementations, otherwise undefined behavior results. When applied to a function which is made available to an `extern` block, the declaration in the `extern` block must also have the attribute, otherwise undefined behavior results.

[attributes.codegen.track_caller.behavior]

### Behavior

Applying the attribute to a function `f` allows code within `f` to get a hint of the `Location` of the “topmost” tracked call that led to `f`’s invocation. At the point of observation, an implementation behaves as if it walks up the stack from `f`’s frame to find the nearest frame of an unattributed function `outer`, and it returns the `Location` of the tracked call in `outer`.

    #![allow(unused)]
    fn main() {
    #[track_caller]
    fn f() {
        println!("{}", std::panic::Location::caller());
    }
    }

> Note

> `core` provides `core::panic::Location::caller` for observing caller locations. It wraps the `core::intrinsics::caller_location` intrinsic implemented by `rustc`.

> Note

> Because the resulting `Location` is a hint, an implementation may halt its walk up the stack early. See Limitations for important caveats.

#### Examples

When `f` is called directly by `calls_f`, code in `f` observes its callsite within `calls_f`:

    #![allow(unused)]
    fn main() {
    #[track_caller]
    fn f() {
        println!("{}", std::panic::Location::caller());
    }
    fn calls_f() {
        f(); // <-- f() prints this location
    }
    }

When `f` is called by another attributed function `g` which is in turn called by `calls_g`, code in both `f` and `g` observes `g`’s callsite within `calls_g`:

    #![allow(unused)]
    fn main() {
    #[track_caller]
    fn f() {
        println!("{}", std::panic::Location::caller());
    }
    #[track_caller]
    fn g() {
        println!("{}", std::panic::Location::caller());
        f();
    }

    fn calls_g() {
        g(); // <-- g() prints this location twice, once itself and once from f()
    }
    }

When `g` is called by another attributed function `h` which is in turn called by `calls_h`, all code in `f`, `g`, and `h` observes `h`’s callsite within `calls_h`:

    #![allow(unused)]
    fn main() {
    #[track_caller]
    fn f() {
        println!("{}", std::panic::Location::caller());
    }
    #[track_caller]
    fn g() {
        println!("{}", std::panic::Location::caller());
        f();
    }
    #[track_caller]
    fn h() {
        println!("{}", std::panic::Location::caller());
        g();
    }

    fn calls_h() {
        h(); // <-- prints this location three times, once itself, once from g(), once from f()
    }
    }

And so on.

[attributes.codegen.track_caller.limits]

### Limitations

[attributes.codegen.track_caller.hint]

This information is a hint and implementations are not required to preserve it.

[attributes.codegen.track_caller.decay]

In particular, coercing a function with `#[track_caller]` to a function pointer creates a shim which appears to observers to have been called at the attributed function’s definition site, losing actual caller information across virtual calls. A common example of this coercion is the creation of a trait object whose methods are attributed.

> Note

> The aforementioned shim for function pointers is necessary because `rustc` implements `track_caller` in a codegen context by appending an implicit parameter to the function ABI, but this would be unsound for an indirect call because the parameter is not a part of the function’s type and a given function pointer type may or may not refer to a function with the attribute. The creation of a shim hides the implicit parameter from callers of the function pointer, preserving soundness.

[attributes.codegen.instruction_set]

## The `instruction_set` attribute

[attributes.codegen.instruction_set.intro]

The `instruction_set` attribute specifies the instruction set that a function will use during code generation. This allows mixing more than one instruction set in a single program.

> Example

>     #[instruction_set(arm::a32)]
>     fn arm_code() {}

>     #[instruction_set(arm::t32)]
>     fn thumb_code() {}

[attributes.codegen.instruction_set.syntax]

The `instruction_set` attribute uses the MetaListPaths syntax to specify a single path consisting of the architecture family name and instruction set name.

[attributes.codegen.instruction_set.allowed-positions]

The `instruction_set` attribute may only be applied to functions with bodies — closures, async blocks, free functions, associated functions in an inherent impl or trait impl, and associated functions in a trait definition when those functions have a default definition .

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

> Note

> Though the attribute can be applied to closures and async blocks, the usefulness of this is limited as we do not yet support attributes on expressions.

[attributes.codegen.instruction_set.duplicates]

The `instruction_set` attribute may be used only once on a function.

[attributes.codegen.instruction_set.target-limits]

The `instruction_set` attribute may only be used with a target that supports the given value.

[attributes.codegen.instruction_set.inline-asm]

When the `instruction_set` attribute is used, any inline assembly in the function must use the specified instruction set instead of the target default.

[attributes.codegen.instruction_set.arm]

### `instruction_set` on ARM

When targeting the `ARMv4T` and `ARMv5te` architectures, the supported values for `instruction_set` are:

- `arm::a32` — Generate the function as A32 “ARM” code.
- `arm::t32` — Generate the function as T32 “Thumb” code.

If the address of the function is taken as a function pointer, the low bit of the address will depend on the selected instruction set:

- For `arm::a32` (“ARM”), it will be 0.
- For `arm::t32` (“Thumb”), it will be 1.

[attributes.limits]

# Limits

The following attributes affect compile-time limits.

[attributes.limits.recursion_limit]

## The `recursion_limit` attribute

[attributes.limits.recursion_limit.intro]

The `recursion_limit` attribute may be applied at the crate level to set the maximum depth for potentially infinitely-recursive compile-time operations like macro expansion or auto-dereference.

[attributes.limits.recursion_limit.syntax]

It uses the MetaNameValueStr syntax to specify the recursion depth.

> Note

> The default in `rustc` is 128.

    #![allow(unused)]
    #![recursion_limit = "4"]

    fn main() {
    macro_rules! a {
        () => { a!(1); };
        (1) => { a!(2); };
        (2) => { a!(3); };
        (3) => { a!(4); };
        (4) => { };
    }

    // This fails to expand because it requires a recursion depth greater than 4.
    a!{}
    }

    #![allow(unused)]
    #![recursion_limit = "1"]

    fn main() {
    // This fails because it requires two recursive steps to auto-dereference.
    (|_: &u8| {})(&&&1);
    }

[attributes.limits.type_length_limit]

## The `type_length_limit` attribute

[attributes.limits.type_length_limit.intro]

The `type_length_limit` attribute sets the maximum number of type substitutions allowed when constructing a concrete type during monomorphization.

> Note

> `rustc` only enforces the limit when the nightly `-Zenforce-type-length-limit` flag is active.

> For more information, see Rust PR #127670.

> Example

>     #![type_length_limit = "4"]

>     fn f<T>(x: T) {}

>     // This fails to compile because monomorphizing to
>     // `f::<((((i32,), i32), i32), i32)>` requires more
>     // than 4 type elements.
>     f(((((1,), 2), 3), 4));

> Note

> The default value in `rustc` is `1048576`.

[attributes.limits.type_length_limit.syntax]

The `type_length_limit` attribute uses the MetaNameValueStr syntax. The value in the string must be a non-negative number.

[attributes.limits.type_length_limit.allowed-positions]

The `type_length_limit` attribute may only be applied to the crate root.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[attributes.limits.type_length_limit.duplicates]

Only the first use of `type_length_limit` on an item has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[attributes.type-system]

# Type system attributes

The following attributes are used for changing how a type can be used.

[attributes.type-system.non_exhaustive]

## The `non_exhaustive` attribute

[attributes.type-system.non_exhaustive.intro]

The `non_exhaustive` attribute indicates that a type or variant may have more fields or variants added in the future.

[attributes.type-system.non_exhaustive.allowed-positions]

It can be applied to `struct`s, `enum`s, and `enum` variants.

[attributes.type-system.non_exhaustive.syntax]

The `non_exhaustive` attribute uses the MetaWord syntax and thus does not take any inputs.

[attributes.type-system.non_exhaustive.same-crate]

Within the defining crate, `non_exhaustive` has no effect.

    #![allow(unused)]
    fn main() {
    #[non_exhaustive]
    pub struct Config {
        pub window_width: u16,
        pub window_height: u16,
    }

    #[non_exhaustive]
    pub struct Token;

    #[non_exhaustive]
    pub struct Id(pub u64);

    #[non_exhaustive]
    pub enum Error {
        Message(String),
        Other,
    }

    pub enum Message {
        #[non_exhaustive] Send { from: u32, to: u32, contents: String },
        #[non_exhaustive] Reaction(u32),
        #[non_exhaustive] Quit,
    }

    // Non-exhaustive structs can be constructed as normal within the defining crate.
    let config = Config { window_width: 640, window_height: 480 };
    let token = Token;
    let id = Id(4);

    // Non-exhaustive structs can be matched on exhaustively within the defining crate.
    let Config { window_width, window_height } = config;
    let Token = token;
    let Id(id_number) = id;

    let error = Error::Other;
    let message = Message::Reaction(3);

    // Non-exhaustive enums can be matched on exhaustively within the defining crate.
    match error {
        Error::Message(ref s) => { },
        Error::Other => { },
    }

    match message {
        // Non-exhaustive variants can be matched on exhaustively within the defining crate.
        Message::Send { from, to, contents } => { },
        Message::Reaction(id) => { },
        Message::Quit => { },
    }
    }

[attributes.type-system.non_exhaustive.external-crate]

Outside of the defining crate, types annotated with `non_exhaustive` have limitations that preserve backwards compatibility when new fields or variants are added.

[attributes.type-system.non_exhaustive.construction]

Non-exhaustive types cannot be constructed outside of the defining crate:

- Non-exhaustive variants (`struct` or `enum` variant) cannot be constructed with a StructExpression (including with functional update syntax).
- The implicitly defined same-named constant of a unit-like struct, or the same-named constructor function of a tuple struct, has a visibility no greater than `pub(crate)`. That is, if the struct’s visibility is `pub`, then the constant or constructor’s visibility is `pub(crate)`, and otherwise the visibility of the two items is the same (as is the case without `#[non_exhaustive]`).
- `enum` instances can be constructed.

The following examples of construction do not compile when outside the defining crate:

    // These are types defined in an upstream crate that have been annotated as
    // `#[non_exhaustive]`.
    use upstream::{Config, Token, Id, Error, Message};

    // Cannot construct an instance of `Config`; if new fields were added in
    // a new version of `upstream` then this would fail to compile, so it is
    // disallowed.
    let config = Config { window_width: 640, window_height: 480 };

    // Cannot construct an instance of `Token`; if new fields were added, then
    // it would not be a unit-like struct any more, so the same-named constant
    // created by it being a unit-like struct is not public outside the crate;
    // this code fails to compile.
    let token = Token;

    // Cannot construct an instance of `Id`; if new fields were added, then
    // its constructor function signature would change, so its constructor
    // function is not public outside the crate; this code fails to compile.
    let id = Id(5);

    // Can construct an instance of `Error`; new variants being introduced would
    // not result in this failing to compile.
    let error = Error::Message("foo".to_string());

    // Cannot construct an instance of `Message::Send` or `Message::Reaction`;
    // if new fields were added in a new version of `upstream` then this would
    // fail to compile, so it is disallowed.
    let message = Message::Send { from: 0, to: 1, contents: "foo".to_string(), };
    let message = Message::Reaction(0);

    // Cannot construct an instance of `Message::Quit`; if this were converted to
    // a tuple enum variant `upstream`, this would fail to compile.
    let message = Message::Quit;

[attributes.type-system.non_exhaustive.match]

There are limitations when matching on non-exhaustive types outside of the defining crate:

- When pattern matching on a non-exhaustive variant (`struct` or `enum` variant), a StructPattern must be used which must include a `..`. A tuple enum variant’s constructor’s visibility is reduced to be no greater than `pub(crate)`.
- When pattern matching on a non-exhaustive `enum`, matching on a variant does not contribute towards the exhaustiveness of the arms. The following examples of matching do not compile when outside the defining crate:

    // These are types defined in an upstream crate that have been annotated as
    // `#[non_exhaustive]`.
    use upstream::{Config, Token, Id, Error, Message};

    // Cannot match on a non-exhaustive enum without including a wildcard arm.
    match error {
      Error::Message(ref s) => { },
      Error::Other => { },
      // would compile with: `_ => {},`
    }

    // Cannot match on a non-exhaustive struct without a wildcard.
    if let Ok(Config { window_width, window_height }) = config {
        // would compile with: `..`
    }

    // Cannot match a non-exhaustive unit-like or tuple struct except by using
    // braced struct syntax with a wildcard.
    // This would compile as `let Token { .. } = token;`
    let Token = token;
    // This would compile as `let Id { 0: id_number, .. } = id;`
    let Id(id_number) = id;

    match message {
      // Cannot match on a non-exhaustive struct enum variant without including a wildcard.
      Message::Send { from, to, contents } => { },
      // Cannot match on a non-exhaustive tuple or unit enum variant.
      Message::Reaction(type) => { },
      Message::Quit => { },
    }

It’s also not allowed to use numeric casts (`as`) on enums that contain any non-exhaustive variants.

For example, the following enum can be cast because it doesn’t contain any non-exhaustive variants:

    #![allow(unused)]
    fn main() {
    #[non_exhaustive]
    pub enum Example {
        First,
        Second
    }
    }

However, if the enum contains even a single non-exhaustive variant, casting will result in an error. Consider this modified version of the same enum:

    #![allow(unused)]
    fn main() {
    #[non_exhaustive]
    pub enum EnumWithNonExhaustiveVariants {
        First,
        #[non_exhaustive]
        Second
    }
    }

    use othercrate::EnumWithNonExhaustiveVariants;

    // Error: cannot cast an enum with a non-exhaustive variant when it's defined in another crate
    let _ = EnumWithNonExhaustiveVariants::First as u8;

Non-exhaustive types are always considered inhabited in downstream crates.

[attributes.debugger]

# Debugger attributes

The following attributes are used for enhancing the debugging experience when using third-party debuggers like GDB or WinDbg.

[attributes.debugger.debugger_visualizer]

## The `debugger_visualizer` attribute

[attributes.debugger.debugger_visualizer.intro]

The `debugger_visualizer` attribute can be used to embed a debugger visualizer file into the debug information. This improves the debugger experience when displaying values.

> Example

>     #![debugger_visualizer(natvis_file = "Example.natvis")]
>     #![debugger_visualizer(gdb_script_file = "example.py")]

[attributes.debugger.debugger_visualizer.syntax]

The `debugger_visualizer` attribute uses the MetaListNameValueStr syntax to specify its inputs. One of the following keys must be specified:

- `natvis_file`
- `gdb_script_file`

[attributes.debugger.debugger_visualizer.allowed-positions]

The `debugger_visualizer` attribute may only be applied to a module or to the crate root.

[attributes.debugger.debugger_visualizer.duplicates]

The `debugger_visualizer` attribute may be used any number of times on a form. All specified visualizer files will be loaded.

[attributes.debugger.debugger_visualizer.natvis]

### Using `debugger_visualizer` with Natvis

[attributes.debugger.debugger_visualizer.natvis.intro]

Natvis is an XML-based framework for Microsoft debuggers (such as Visual Studio and WinDbg) that uses declarative rules to customize the display of types. For detailed information on the Natvis format, refer to Microsoft’s Natvis documentation.

[attributes.debugger.debugger_visualizer.natvis.msvc]

This attribute only supports embedding Natvis files on `-windows-msvc` targets.

[attributes.debugger.debugger_visualizer.natvis.path]

The path to the Natvis file is specified with the `natvis_file` key, which is a path relative to the source file.

> Example

>     #![debugger_visualizer(natvis_file = "Rectangle.natvis")]

>     struct FancyRect {
>         x: f32,
>         y: f32,
>         dx: f32,
>         dy: f32,
>     }

>     fn main() {
>         let fancy_rect = FancyRect { x: 10.0, y: 10.0, dx: 5.0, dy: 5.0 };
>         println!("set breakpoint here");
>     }

> `Rectangle.natvis` contains:

>     <?xml version="1.0" encoding="utf-8"?>
>     <AutoVisualizer xmlns="http://schemas.microsoft.com/vstudio/debugger/natvis/2010">
>         <Type Name="foo::FancyRect">
>           <DisplayString>({x},{y}) + ({dx}, {dy})</DisplayString>
>           <Expand>
>             <Synthetic Name="LowerLeft">
>               <DisplayString>({x}, {y})</DisplayString>
>             </Synthetic>
>             <Synthetic Name="UpperLeft">
>               <DisplayString>({x}, {y + dy})</DisplayString>
>             </Synthetic>
>             <Synthetic Name="UpperRight">
>               <DisplayString>({x + dx}, {y + dy})</DisplayString>
>             </Synthetic>
>             <Synthetic Name="LowerRight">
>               <DisplayString>({x + dx}, {y})</DisplayString>
>             </Synthetic>
>           </Expand>
>         </Type>
>     </AutoVisualizer>

> When viewed under WinDbg, the `fancy_rect` variable would be shown as follows:

>     > Variables:
>       > fancy_rect: (10.0, 10.0) + (5.0, 5.0)
>         > LowerLeft: (10.0, 10.0)
>         > UpperLeft: (10.0, 15.0)
>         > UpperRight: (15.0, 15.0)
>         > LowerRight: (15.0, 10.0)

[attributes.debugger.debugger_visualizer.gdb]

### Using `debugger_visualizer` with GDB

[attributes.debugger.debugger_visualizer.gdb.pretty]

GDB supports the use of a structured Python script, called a pretty printer, that describes how a type should be visualized in the debugger view. For detailed information on pretty printers, refer to GDB’s pretty printing documentation.

> Note

> Embedded pretty printers are not automatically loaded when debugging a binary under GDB.

> There are two ways to enable auto-loading embedded pretty printers:

> 1. Launch GDB with extra arguments to explicitly add a directory or binary to the auto-load safe path: `gdb -iex "add-auto-load-safe-path safe-path path/to/binary" path/to/binary` For more information, see GDB’s auto-loading documentation.
> 2. Create a file named `gdbinit` under `$HOME/.config/gdb` (you may need to create the directory if it doesn’t already exist). Add the following line to that file: `add-auto-load-safe-path path/to/binary`.

[attributes.debugger.debugger_visualizer.gdb.path]

These scripts are embedded using the `gdb_script_file` key, which is a path relative to the source file.

> Example

>     #![debugger_visualizer(gdb_script_file = "printer.py")]

>     struct Person {
>         name: String,
>         age: i32,
>     }

>     fn main() {
>         let bob = Person { name: String::from("Bob"), age: 10 };
>         println!("set breakpoint here");
>     }

> `printer.py` contains:

>     import gdb

>     class PersonPrinter:
>         "Print a Person"

>         def __init__(self, val):
>             self.val = val
>             self.name = val["name"]
>             self.age = int(val["age"])

>         def to_string(self):
>             return "{} is {} years old.".format(self.name, self.age)

>     def lookup(val):
>         lookup_tag = val.type.tag
>         if lookup_tag is None:
>             return None
>         if "foo::Person" == lookup_tag:
>             return PersonPrinter(val)

>         return None

>     gdb.current_objfile().pretty_printers.append(lookup)

> When the crate’s debug executable is passed into GDB1, `print bob` will display:

>     "Bob" is 10 years old.

[attributes.debugger.collapse_debuginfo]

## The `collapse_debuginfo` attribute

[attributes.debugger.collapse_debuginfo.intro]

The `collapse_debuginfo` attribute controls whether code locations from a macro definition are collapsed into a single location associated with the macro’s call site when generating debuginfo for code calling this macro.

> Example

>     #![allow(unused)]
>     fn main() {
>     #[collapse_debuginfo(yes)]
>     macro_rules! example {
>         () => {
>             println!("hello!");
>         };
>     }
>     }

> When using a debugger, invoking the `example` macro may appear as though it is calling a function. That is, when you step to the invocation site, it may show the macro invocation rather than the expanded code.

[attributes.debugger.collapse_debuginfo.syntax]

The syntax for the `collapse_debuginfo` attribute is:

Syntax
CollapseDebuginfoAttribute → collapse_debuginfo ( CollapseDebuginfoOption )

CollapseDebuginfoOption →
yes
| no
| external

[attributes.debugger.collapse_debuginfo.allowed-positions]

The `collapse_debuginfo` attribute may only be applied to a `macro_rules` definition.

[attributes.debugger.collapse_debuginfo.duplicates]

The `collapse_debuginfo` attribute may used only once on a macro.

[attributes.debugger.collapse_debuginfo.options]

The `collapse_debuginfo` attribute accepts these options:

- `#[collapse_debuginfo(yes)]` — Code locations in debuginfo are collapsed.
- `#[collapse_debuginfo(no)]` — Code locations in debuginfo are not collapsed.
- `#[collapse_debuginfo(external)]` — Code locations in debuginfo are collapsed only if the macro comes from a different crate.

[attributes.debugger.collapse_debuginfo.default]

The `external` behavior is the default for macros that don’t have this attribute unless they are built-in macros. For built-in macros the default is `yes`.

> Note

> `rustc` has a `-C collapse-macro-debuginfo` CLI option to override both the default behavior and the values of any `#[collapse_debuginfo]` attributes.

1. Note: This assumes you are using the `rust-gdb` script which configures pretty-printers for standard library types like `String`. ↩

[stmt-expr]

# Statements and expressions

Rust is primarily an expression language. This means that most forms of value-producing or effect-causing evaluation are directed by the uniform syntax category of expressions. Each kind of expression can typically nest within each other kind of expression, and rules for evaluation of expressions involve specifying both the value produced by the expression and the order in which its sub-expressions are themselves evaluated.

In contrast, statements serve mostly to contain and explicitly sequence expression evaluation.

[statement]

# Statements

[statement.syntax]

Syntax
Statement →
;
| Item
| LetStatement
| ExpressionStatement
| OuterAttribute* MacroInvocationSemi

[statement.intro]

A statement is a component of a block, which is in turn a component of an outer expression or function.

[statement.kind]

Rust has two kinds of statement: declaration statements and expression statements.

[statement.decl]

## Declaration statements

A declaration statement is one that introduces one or more names into the enclosing statement block. The declared names may denote new variables or new items.

The two kinds of declaration statements are item declarations and `let` statements.

[statement.item]

### Item declarations

[statement.item.intro]

An item declaration statement has a syntactic form identical to an item declaration within a module.

[statement.item.scope]

Declaring an item within a statement block restricts its scope to the block containing the statement. The item is not given a canonical path nor are any sub-items it may declare.

[statement.item.associated-scope]

The exception to this is that associated items defined by implementations are still accessible in outer scopes as long as the item and, if applicable, trait are accessible. It is otherwise identical in meaning to declaring the item inside a module.

[statement.item.outer-generics]

There is no implicit capture of the containing function’s generic parameters, parameters, and local variables. For example, `inner` may not access `outer_var`.

    #![allow(unused)]
    fn main() {
    fn outer() {
      let outer_var = true;

      fn inner() { /* outer_var is not in scope here */ }

      inner();
    }
    }

[statement.let]

### `let` statements

[statement.let.syntax]

Syntax
LetStatement →
OuterAttribute* let PatternNoTopAlt ( : Type )?
(
= Expression
| = Expressionexcept LazyBooleanExpression or end with a `}` else BlockExpression
)? ;

[statement.let.intro]

A `let` statement introduces a new set of variables, given by a pattern. The pattern is followed optionally by a type annotation and then either ends, or is followed by an initializer expression plus an optional `else` block.

[statement.let.inference]

When no type annotation is given, the compiler will infer the type, or signal an error if insufficient type information is available for definite inference.

[statement.let.scope]

Any variables introduced by a variable declaration are visible from the point of declaration until the end of the enclosing block scope, except when they are shadowed by another variable declaration.

[statement.let.constraint]

If an `else` block is not present, the pattern must be irrefutable. If an `else` block is present, the pattern may be refutable.

[statement.let.behavior]

If the pattern does not match (this requires it to be refutable), the `else` block is executed. The `else` block must always diverge (evaluate to the never type).

    #![allow(unused)]
    fn main() {
    let (mut v, w) = (vec![1, 2, 3], 42); // The bindings may be mut or const
    let Some(t) = v.pop() else { // Refutable patterns require an else block
        panic!(); // The else block must diverge
    };
    let [u, v] = [v[0], v[1]] else { // This pattern is irrefutable, so the compiler
                                     // will lint as the else block is redundant.
        panic!();
    };
    }

[statement.expr]

## Expression statements

[statement.expr.syntax]

Syntax
ExpressionStatement →
ExpressionWithoutBlock ;
| ExpressionWithBlock ;?

[statement.expr.intro]

An expression statement is one that evaluates an expression and ignores its result. As a rule, an expression statement’s purpose is to trigger the effects of evaluating its expression.

[statement.expr.restriction-semicolon]

An expression that consists of only a block expression or control flow expression, if used in a context where a statement is permitted, can omit the trailing semicolon. This can cause an ambiguity between it being parsed as a standalone statement and as a part of another expression; in this case, it is parsed as a statement.

[statement.expr.constraint-block]

The type of ExpressionWithBlock expressions when used as statements must be the unit type.

    #![allow(unused)]
    fn main() {
    let mut v = vec![1, 2, 3];
    v.pop();          // Ignore the element returned from pop
    if v.is_empty() {
        v.push(5);
    } else {
        v.remove(0);
    }                 // Semicolon can be omitted.
    [1];              // Separate expression statement, not an indexing expression.
    }

When the trailing semicolon is omitted, the result must be type `()`.

    #![allow(unused)]
    fn main() {
    // bad: the block's type is i32, not ()
    // Error: expected `()` because of default return type
    // if true {
    //   1
    // }

    // good: the block's type is i32
    if true {
      1
    } else {
      2
    };
    }

[statement.attribute]

## Attributes on statements

Statements accept outer attributes. The attributes that have meaning on a statement are `cfg`, and the lint check attributes.

[expr]

# Expressions

[expr.syntax]

Syntax
Expression →
ExpressionWithoutBlock
| ExpressionWithBlock

ExpressionWithoutBlock →
OuterAttribute*
(
LiteralExpression
| PathExpression
| OperatorExpression
| GroupedExpression
| ArrayExpression
| AwaitExpression
| IndexExpression
| TupleExpression
| TupleIndexingExpression
| StructExpression
| CallExpression
| MethodCallExpression
| FieldExpression
| ClosureExpression
| AsyncBlockExpression
| ContinueExpression
| BreakExpression
| RangeExpression
| ReturnExpression
| UnderscoreExpression
| MacroInvocation
)

ExpressionWithBlock →
OuterAttribute*
(
BlockExpression
| ConstBlockExpression
| UnsafeBlockExpression
| LoopExpression
| IfExpression
| MatchExpression
)

[expr.intro]

An expression may have two roles: it always produces a value, and it may have effects (otherwise known as “side effects”).

[expr.evaluation]

An expression evaluates to a value, and has effects during evaluation.

[expr.operands]

Many expressions contain sub-expressions, called the operands of the expression.

[expr.behavior]

The meaning of each kind of expression dictates several things:

- Whether or not to evaluate the operands when evaluating the expression
- The order in which to evaluate the operands
- How to combine the operands’ values to obtain the value of the expression

[expr.structure]

In this way, the structure of expressions dictates the structure of execution. Blocks are just another kind of expression, so blocks, statements, expressions, and blocks again can recursively nest inside each other to an arbitrary depth.

> Note

> We give names to the operands of expressions so that we may discuss them, but these names are not stable and may be changed.

[expr.precedence]

## Expression precedence

The precedence of Rust operators and expressions is ordered as follows, going from strong to weak. Binary Operators at the same precedence level are grouped in the order given by their associativity.

Operator/Expression | Associativity
--- | ---
Paths |
Method calls |
Field expressions | left to right
Function calls, array indexing |
`?` |
Unary `-` `!` `*` borrow |
`as` | left to right
`*` `/` `%` | left to right
`+` `-` | left to right
`<<` `>>` | left to right
`&` | left to right
`^` | left to right
`|` | left to right
`==` `!=` `<` `>` `<=` `>=` | Require parentheses
`&&` | left to right
`||` | left to right
`..` `..=` | Require parentheses
`=` `+=` `-=` `*=` `/=` `%=` `&=` `|=` `^=` `<<=` `>>=` | right to left
`return` `break` closures |

[expr.operand-order]

## Evaluation order of operands

[expr.operand-order.default]

The following list of expressions all evaluate their operands the same way, as described after the list. Other expressions either don’t take operands or evaluate them conditionally as described on their respective pages.

- Dereference expression
- Error propagation expression
- Negation expression
- Arithmetic and logical binary operators
- Comparison operators
- Type cast expression
- Grouped expression
- Array expression
- Await expression
- Index expression
- Tuple expression
- Tuple index expression
- Struct expression
- Call expression
- Method call expression
- Field expression
- Break expression
- Range expression
- Return expression

[expr.operand-order.operands-before-primary]

The operands of these expressions are evaluated prior to applying the effects of the expression. Expressions taking multiple operands are evaluated left to right as written in the source code.

> Note

> Which subexpressions are the operands of an expression is determined by expression precedence as per the previous section.

For example, the two `next` method calls will always be called in the same order:

    #![allow(unused)]
    fn main() {
    // Using vec instead of array to avoid references
    // since there is no stable owned array iterator
    // at the time this example was written.
    let mut one_two = vec![1, 2].into_iter();
    assert_eq!(
        (1, 2),
        (one_two.next().unwrap(), one_two.next().unwrap())
    );
    }

> Note

> Since this is applied recursively, these expressions are also evaluated from innermost to outermost, ignoring siblings until there are no inner subexpressions.

[expr.place-value]

## Place expressions and value expressions

[expr.place-value.intro]

Expressions are divided into two main categories: place expressions and value expressions; there is also a third, minor category of expressions called assignee expressions. Within each expression, operands may likewise occur in either place context or value context. The evaluation of an expression depends both on its own category and the context it occurs within.

[expr.place-value.place-memory-location]

A place expression is an expression that represents a memory location.

[expr.place-value.place-expr-kinds]

These expressions are paths which refer to local variables, static variables, dereferences (`*expr`), array indexing expressions (`expr[expr]`), field references (`expr.f`) and parenthesized place expressions.

[expr.place-value.value-expr-kinds]

All other expressions are value expressions.

[expr.place-value.value-result]

A value expression is an expression that represents an actual value.

[expr.place-value.place-context]

The following contexts are place expression contexts:

- The left operand of a compound assignment expression.
- The operand of a unary borrow, raw borrow or dereference operator.
- The operand of a field expression.
- The indexed operand of an array indexing expression.
- The operand of any implicit borrow.
- The initializer of a let statement.
- The scrutinee of an `if let`, `match`, or `while let` expression.
- The base of a functional update struct expression.

> Note

> Historically, place expressions were called lvalues and value expressions were called rvalues.

[expr.place-value.assignee]

An assignee expression is an expression that appears in the left operand of an assignment expression. Explicitly, the assignee expressions are:

- Place expressions.
- Underscores.
- Tuples of assignee expressions.
- Slices of assignee expressions.
- Tuple structs of assignee expressions.
- Structs of assignee expressions (with optionally named fields).
- Unit structs

[expr.place-value.parenthesis]

Arbitrary parenthesisation is permitted inside assignee expressions.

[expr.move]

### Moved and copied types

[expr.move.intro]

When a place expression is evaluated in a value expression context, or is bound by value in a pattern, it denotes the value held in that memory location.

[expr.move.copy]

If the type of that value implements `Copy`, then the value will be copied.

[expr.move.requires-sized]

In the remaining situations, if that type is `Sized`, then it may be possible to move the value.

[expr.move.movable-place]

Only the following place expressions may be moved out of:

- Variables which are not currently borrowed.
- Temporary values.
- Fields of a place expression which can be moved out of and don’t implement `Drop`.
- The result of dereferencing an expression with type `Box<T>` and that can also be moved out of.

[expr.move.deinitialization]

After moving out of a place expression that evaluates to a local variable, the location is deinitialized and cannot be read from again until it is reinitialized.

[expr.move.place-invalid]

In all other cases, trying to use a place expression in a value expression context is an error.

[expr.mut]

### Mutability

[expr.mut.intro]

For a place expression to be assigned to, mutably borrowed, implicitly mutably borrowed, or bound to a pattern containing `ref mut`, it must be mutable. We call these mutable place expressions. In contrast, other place expressions are called immutable place expressions.

[expr.mut.valid-places]

The following expressions can be mutable place expression contexts:

- Mutable variables which are not currently borrowed.
- Mutable `static` items.
- Temporary values.
- Fields: this evaluates the subexpression in a mutable place expression context.
- Dereferences of a `*mut T` pointer.
- Dereference of a variable, or field of a variable, with type `&mut T`. Note: This is an exception to the requirement of the next rule.
- Dereferences of a type that implements `DerefMut`: this then requires that the value being dereferenced is evaluated in a mutable place expression context.
- Array indexing of a type that implements `IndexMut`: this then evaluates the value being indexed, but not the index, in mutable place expression context.

[expr.temporary]

### Temporaries

When using a value expression in most place expression contexts, a temporary unnamed memory location is created and initialized to that value. The expression evaluates to that location instead, except if promoted to a `static`. The drop scope of the temporary is usually the end of the enclosing statement.

[expr.super-macros]

### Super macros

[expr.super-macros.intro]

Certain built-in macros may create temporaries whose scopes may be extended. These temporaries are super temporaries and these macros are super macros. Invocations of these macros are super macro call expressions. Arguments to these macros may be super operands.

> Note

> When a super macro call expression is an extending expression, its super operands are extending expressions and the scopes of the super temporaries are extended. See destructors.scope.lifetime-extension.exprs.

[expr.super-macros.format_args]

#### `format_args!`

[expr.super-macros.format_args.super-operands]

Except for the format string argument, all arguments passed to `format_args!` are super operands.

    #![allow(unused)]
    fn main() {
    fn temp() -> String { String::from("") }
    // Due to the call being an extending expression and the argument
    // being a super operand, the inner block is an extending expression,
    // so the scope of the temporary created in its trailing expression
    // is extended.
    let _ = format_args!("{}", { &temp() }); // OK
    }

[expr.super-macros.format_args.super-temporaries]

The super operands of `format_args!` are implicitly borrowed and are therefore place expression contexts. When a value expression is passed as an argument, it creates a super temporary.

    #![allow(unused)]
    fn main() {
    fn temp() -> String { String::from("") }
    let x = format_args!("{}", temp());
    x; // <-- The temporary is extended, allowing use here.
    }

The expansion of a call to `format_args!` sometimes creates other internal super temporaries.

    #![allow(unused)]
    fn main() {
    let x = {
        // This call creates an internal temporary.
        let x = format_args!("{:?}", 0);
        x // <-- The temporary is extended, allowing its use here.
    }; // <-- The temporary is dropped here.
    x; // ERROR
    }

    #![allow(unused)]
    fn main() {
    // This call doesn't create an internal temporary.
    let x = { let x = format_args!("{}", 0); x };
    x; // OK
    }

> Note

> The details of when `format_args!` does or does not create internal temporaries are currently unspecified.

[expr.super-macros.pin]

#### `pin!`

[expr.super-macros.pin.super-operands]

The argument to `pin!` is a super operand.

    #![allow(unused)]
    fn main() {
    use core::pin::pin;
    fn temp() {}
    // As above for `format_args!`.
    let _ = pin!({ &temp() }); // OK
    }

[expr.super-macros.pin.super-temporaries]

The argument to `pin!` is a value expression context and creates a super temporary.

    #![allow(unused)]
    fn main() {
    use core::pin::pin;
    fn temp() {}
    // The argument is evaluated into a super temporary.
    let x = pin!(temp());
    // The temporary is extended, allowing its use here.
    x; // OK
    }

[expr.implicit-borrow]

### Implicit borrows

[expr.implicit-borrow-intro]

Certain expressions will treat an expression as a place expression by implicitly borrowing it. For example, it is possible to compare two unsized slices for equality directly, because the `==` operator implicitly borrows its operands:

    #![allow(unused)]
    fn main() {
    let c = [1, 2, 3];
    let d = vec![1, 2, 3];
    let a: &[i32];
    let b: &[i32];
    a = &c;
    b = &d;
    // ...
    *a == *b;
    // Equivalent form:
    ::std::cmp::PartialEq::eq(&*a, &*b);
    }

[expr.implicit-borrow.application]

Implicit borrows may be taken in the following expressions:

- Left operand in method-call expressions.
- Left operand in field expressions.
- Left operand in call expressions.
- Left operand in array indexing expressions.
- Operand of the dereference operator (`*`).
- Operands of comparison.
- Left operands of the compound assignment.
- Arguments to `format_args!` except the format string.

[expr.overload]

## Overloading traits

Many of the following operators and expressions can also be overloaded for other types using traits in `std::ops` or `std::cmp`. These traits also exist in `core::ops` and `core::cmp` with the same names.

[expr.attr]

## Expression attributes

[expr.attr.restriction]

Outer attributes before an expression are allowed only in a few specific cases:

- Before an expression used as a statement.
- Elements of array expressions, tuple expressions, call expressions, and tuple-style struct expressions.
- The tail expression of block expressions.

[expr.attr.never-before]

They are never allowed before:

- Range expressions.
- Binary operator expressions (ArithmeticOrLogicalExpression, ComparisonExpression, LazyBooleanExpression, TypeCastExpression, AssignmentExpression, CompoundAssignmentExpression).

[expr.literal]

# Literal expressions

[expr.literal.syntax]

Syntax
LiteralExpression →
CHAR_LITERAL
| STRING_LITERAL
| RAW_STRING_LITERAL
| BYTE_LITERAL
| BYTE_STRING_LITERAL
| RAW_BYTE_STRING_LITERAL
| C_STRING_LITERAL
| RAW_C_STRING_LITERAL
| INTEGER_LITERAL
| FLOAT_LITERAL
| true
| false

[expr.literal.intro]

A literal expression is an expression consisting of a single token, rather than a sequence of tokens, that immediately and directly denotes the value it evaluates to, rather than referring to it by name or some other evaluation rule.

[expr.literal.const-expr]

A literal is a form of constant expression, so is evaluated (primarily) at compile time.

[expr.literal.literal-token]

Each of the lexical literal forms described earlier can make up a literal expression, as can the keywords `true` and `false`.

    #![allow(unused)]
    fn main() {
    "hello";   // string type
    '5';       // character type
    5;         // integer type
    }

[expr.literal.string-representation]

In the descriptions below, the string representation of a token is the sequence of characters from the input which matched the token’s production in a Lexer grammar snippet.

> Note

> This string representation never includes a character `U+000D` (CR) immediately followed by `U+000A` (LF): this pair would have been previously transformed into a single `U+000A` (LF).

[expr.literal.escape]

## Escapes

[expr.literal.escape.intro]

The descriptions of textual literal expressions below make use of several forms of escape.

[expr.literal.escape.sequence]

Each form of escape is characterised by:

- an escape sequence: a sequence of characters, which always begins with `U+005C` (`\`)
- an escaped value: either a single character or an empty sequence of characters

In the definitions of escapes below:

- An octal digit is any of the characters in the range [`0`-`7`].
- A hexadecimal digit is any of the characters in the ranges [`0`-`9`], [`a`-`f`], or [`A`-`F`].

[expr.literal.escape.simple]

### Simple escapes

Each sequence of characters occurring in the first column of the following table is an escape sequence.

In each case, the escaped value is the character given in the corresponding entry in the second column.

Escape sequence | Escaped value
--- | ---
`\0` | U+0000 (NUL)
`\t` | U+0009 (HT)
`\n` | U+000A (LF)
`\r` | U+000D (CR)
`\"` | U+0022 (QUOTATION MARK)
`\'` | U+0027 (APOSTROPHE)
`\\` | U+005C (REVERSE SOLIDUS)

[expr.literal.escape.hex-octet]

### 8-bit escapes

The escape sequence consists of `\x` followed by two hexadecimal digits.

The escaped value is the character whose Unicode scalar value is the result of interpreting the final two characters in the escape sequence as a hexadecimal integer, as if by `u8::from_str_radix` with radix 16.

> Note

> The escaped value therefore has a Unicode scalar value in the range of `u8`.

[expr.literal.escape.hex-ascii]

### 7-bit escapes

The escape sequence consists of `\x` followed by an octal digit then a hexadecimal digit.

The escaped value is the character whose Unicode scalar value is the result of interpreting the final two characters in the escape sequence as a hexadecimal integer, as if by `u8::from_str_radix` with radix 16.

[expr.literal.escape.unicode]

### Unicode escapes

The escape sequence consists of `\u{`, followed by a sequence of characters each of which is a hexadecimal digit or `_`, followed by `}`.

The escaped value is the character whose Unicode scalar value is the result of interpreting the hexadecimal digits contained in the escape sequence as a hexadecimal integer, as if by `u32::from_str_radix` with radix 16.

> Note

> The permitted forms of a CHAR_LITERAL or STRING_LITERAL token ensure that there is such a character.

[expr.literal.continuation]

### String continuation escapes

The escape sequence consists of `\` followed immediately by `U+000A` (LF), and all following whitespace characters before the next non-whitespace character. For this purpose, the whitespace characters are `U+0009` (HT), `U+000A` (LF), `U+000D` (CR), and `U+0020` (SPACE).

The escaped value is an empty sequence of characters.

> Note

> The effect of this form of escape is that a string continuation skips following whitespace, including additional newlines. Thus `a`, `b` and `c` are equal:

>     #![allow(unused)]
>     fn main() {
>     let a = "foobar";
>     let b = "foo\
>              bar";
>     let c = "foo\

>          bar";

>     assert_eq!(a, b);
>     assert_eq!(b, c);
>     }

> Skipping additional newlines (as in example c) is potentially confusing and unexpected. This behavior may be adjusted in the future. Until a decision is made, it is recommended to avoid relying on skipping multiple newlines with line continuations. See this issue for more information.

[expr.literal.char]

## Character literal expressions

[expr.literal.char.intro]

A character literal expression consists of a single CHAR_LITERAL token.

[expr.literal.char.type]

The expression’s type is the primitive `char` type.

[expr.literal.char.no-suffix]

The token must not have a suffix.

[expr.literal.char.literal-content]

The token’s literal content is the sequence of characters following the first `U+0027` (`'`) and preceding the last `U+0027` (`'`) in the string representation of the token.

[expr.literal.char.represented]

The literal expression’s represented character is derived from the literal content as follows:

[expr.literal.char.escape]

- If the literal content is one of the following forms of escape sequence, the represented character is the escape sequence’s escaped value:
  - Simple escapes
  - 7-bit escapes
  - Unicode escapes

[expr.literal.char.single]

- Otherwise the represented character is the single character that makes up the literal content.

[expr.literal.char.result]

The expression’s value is the `char` corresponding to the represented character’s Unicode scalar value.

> Note

> The permitted forms of a CHAR_LITERAL token ensure that these rules always produce a single character.

Examples of character literal expressions:

    #![allow(unused)]
    fn main() {
    'R';                               // R
    '\'';                              // '
    '\x52';                            // R
    '\u{00E6}';                        // LATIN SMALL LETTER AE (U+00E6)
    }

[expr.literal.string]

## String literal expressions

[expr.literal.string.intro]

A string literal expression consists of a single STRING_LITERAL or RAW_STRING_LITERAL token.

[expr.literal.string.type]

The expression’s type is a shared reference (with `static` lifetime) to the primitive `str` type. That is, the type is `&'static str`.

[expr.literal.string.no-suffix]

The token must not have a suffix.

[expr.literal.string.literal-content]

The token’s literal content is the sequence of characters following the first `U+0022` (`"`) and preceding the last `U+0022` (`"`) in the string representation of the token.

[expr.literal.string.represented]

The literal expression’s represented string is a sequence of characters derived from the literal content as follows:

[expr.literal.string.escape]

- If the token is a STRING_LITERAL, each escape sequence of any of the following forms occurring in the literal content is replaced by the escape sequence’s escaped value.

  - Simple escapes
  - 7-bit escapes
  - Unicode escapes
  - String continuation escapes

  These replacements take place in left-to-right order. For example, the token `"\\x41"` is converted to the characters `\` `x` `4` `1`.

[expr.literal.string.raw]

- If the token is a RAW_STRING_LITERAL, the represented string is identical to the literal content.

[expr.literal.string.result]

The expression’s value is a reference to a statically allocated `str` containing the UTF-8 encoding of the represented string.

Examples of string literal expressions:

    #![allow(unused)]
    fn main() {
    "foo"; r"foo";                     // foo
    "\"foo\""; r#""foo""#;             // "foo"

    "foo #\"# bar";
    r##"foo #"# bar"##;                // foo #"# bar

    "\x52"; "R"; r"R";                 // R
    "\\x52"; r"\x52";                  // \x52
    }

[expr.literal.byte-char]

## Byte literal expressions

[expr.literal.byte-char.intro]

A byte literal expression consists of a single BYTE_LITERAL token.

[expr.literal.byte-char.literal]

The expression’s type is the primitive `u8` type.

[expr.literal.byte-char.no-suffix]

The token must not have a suffix.

[expr.literal.byte-char.literal-content]

The token’s literal content is the sequence of characters following the first `U+0027` (`'`) and preceding the last `U+0027` (`'`) in the string representation of the token.

[expr.literal.byte-char.represented]

The literal expression’s represented character is derived from the literal content as follows:

[expr.literal.byte-char.escape]

- If the literal content is one of the following forms of escape sequence, the represented character is the escape sequence’s escaped value:
  - Simple escapes
  - 8-bit escapes

[expr.literal.byte-char.single]

- Otherwise the represented character is the single character that makes up the literal content.

[expr.literal.byte-char.result]

The expression’s value is the represented character’s Unicode scalar value.

> Note

> The permitted forms of a BYTE_LITERAL token ensure that these rules always produce a single character, whose Unicode scalar value is in the range of `u8`.

Examples of byte literal expressions:

    #![allow(unused)]
    fn main() {
    b'R';                              // 82
    b'\'';                             // 39
    b'\x52';                           // 82
    b'\xA0';                           // 160
    }

[expr.literal.byte-string]

## Byte string literal expressions

[expr.literal.byte-string.intro]

A byte string literal expression consists of a single BYTE_STRING_LITERAL or RAW_BYTE_STRING_LITERAL token.

[expr.literal.byte-string.type]

The expression’s type is a shared reference (with `static` lifetime) to an array whose element type is `u8`. That is, the type is `&'static [u8; N]`, where `N` is the number of bytes in the represented string described below.

[expr.literal.byte-string.no-suffix]

The token must not have a suffix.

[expr.literal.byte-string.literal-content]

The token’s literal content is the sequence of characters following the first `U+0022` (`"`) and preceding the last `U+0022` (`"`) in the string representation of the token.

[expr.literal.byte-string.represented]

The literal expression’s represented string is a sequence of characters derived from the literal content as follows:

[expr.literal.byte-string.escape]

- If the token is a BYTE_STRING_LITERAL, each escape sequence of any of the following forms occurring in the literal content is replaced by the escape sequence’s escaped value.

  - Simple escapes
  - 8-bit escapes
  - String continuation escapes

  These replacements take place in left-to-right order. For example, the token `b"\\x41"` is converted to the characters `\` `x` `4` `1`.

[expr.literal.byte-string.raw]

- If the token is a RAW_BYTE_STRING_LITERAL, the represented string is identical to the literal content.

[expr.literal.byte-string.result]

The expression’s value is a reference to a statically allocated array containing the Unicode scalar values of the characters in the represented string, in the same order.

> Note

> The permitted forms of BYTE_STRING_LITERAL and RAW_BYTE_STRING_LITERAL tokens ensure that these rules always produce array element values in the range of `u8`.

Examples of byte string literal expressions:

    #![allow(unused)]
    fn main() {
    b"foo"; br"foo";                     // foo
    b"\"foo\""; br#""foo""#;             // "foo"

    b"foo #\"# bar";
    br##"foo #"# bar"##;                 // foo #"# bar

    b"\x52"; b"R"; br"R";                // R
    b"\\x52"; br"\x52";                  // \x52
    }

[expr.literal.c-string]

## C string literal expressions

[expr.literal.c-string.intro]

A C string literal expression consists of a single C_STRING_LITERAL or RAW_C_STRING_LITERAL token.

[expr.literal.c-string.type]

The expression’s type is a shared reference (with `static` lifetime) to the standard library CStr type. That is, the type is `&'static core::ffi::CStr`.

[expr.literal.c-string.no-suffix]

The token must not have a suffix.

[expr.literal.c-string.literal-content]

The token’s literal content is the sequence of characters following the first `"` and preceding the last `"` in the string representation of the token.

[expr.literal.c-string.represented]

The literal expression’s represented bytes are a sequence of bytes derived from the literal content as follows:

[expr.literal.c-string.escape]

- If the token is a C_STRING_LITERAL, the literal content is treated as a sequence of items, each of which is either a single Unicode character other than `\` or an escape. The sequence of items is converted to a sequence of bytes as follows:
  - Each single Unicode character contributes its UTF-8 representation.
  - Each simple escape contributes the Unicode scalar value of its escaped value.
  - Each 8-bit escape contributes a single byte containing the Unicode scalar value of its escaped value.
  - Each unicode escape contributes the UTF-8 representation of its escaped value.
  - Each string continuation escape contributes no bytes.

[expr.literal.c-string.raw]

- If the token is a RAW_C_STRING_LITERAL, the represented bytes are the UTF-8 encoding of the literal content.

> Note

> The permitted forms of C_STRING_LITERAL and RAW_C_STRING_LITERAL tokens ensure that the represented bytes never include a null byte.

[expr.literal.c-string.result]

The expression’s value is a reference to a statically allocated CStr whose array of bytes contains the represented bytes followed by a null byte.

Examples of C string literal expressions:

    #![allow(unused)]
    fn main() {
    c"foo"; cr"foo";                     // foo
    c"\"foo\""; cr#""foo""#;             // "foo"

    c"foo #\"# bar";
    cr##"foo #"# bar"##;                 // foo #"# bar

    c"\x52"; c"R"; cr"R";                // R
    c"\\x52"; cr"\x52";                  // \x52

    c"æ";                                // LATIN SMALL LETTER AE (U+00E6)
    c"\u{00E6}";                         // LATIN SMALL LETTER AE (U+00E6)
    c"\xC3\xA6";                         // LATIN SMALL LETTER AE (U+00E6)

    c"\xE6".to_bytes();                  // [230]
    c"\u{00E6}".to_bytes();              // [195, 166]
    }

[expr.literal.int]

## Integer literal expressions

[expr.literal.int.intro]

An integer literal expression consists of a single INTEGER_LITERAL token.

[expr.literal.int.suffix]

If the token has a suffix, the suffix must be the name of one of the primitive integer types: `u8`, `i8`, `u16`, `i16`, `u32`, `i32`, `u64`, `i64`, `u128`, `i128`, `usize`, or `isize`, and the expression has that type.

[expr.literal.int.infer]

If the token has no suffix, the expression’s type is determined by type inference:

[expr.literal.int.inference-unique-type]

- If an integer type can be uniquely determined from the surrounding program context, the expression has that type.

[expr.literal.int.inference-default]

- If the program context under-constrains the type, it defaults to the signed 32-bit integer `i32`.

[expr.literal.int.inference-error]

- If the program context over-constrains the type, it is considered a static type error.

Examples of integer literal expressions:

    #![allow(unused)]
    fn main() {
    123;                               // type i32
    123i32;                            // type i32
    123u32;                            // type u32
    123_u32;                           // type u32
    let a: u64 = 123;                  // type u64

    0xff;                              // type i32
    0xff_u8;                           // type u8

    0o70;                              // type i32
    0o70_i16;                          // type i16

    0b1111_1111_1001_0000;             // type i32
    0b1111_1111_1001_0000i64;          // type i64

    0usize;                            // type usize
    }

[expr.literal.int.representation]

The value of the expression is determined from the string representation of the token as follows:

[expr.literal.int.radix]

- An integer radix is chosen by inspecting the first two characters of the string, as follows:

  - `0b` indicates radix 2
  - `0o` indicates radix 8
  - `0x` indicates radix 16
  - otherwise the radix is 10.

[expr.literal.int.radix-prefix-stripped]

- If the radix is not 10, the first two characters are removed from the string.

[expr.literal.int.type-suffix-stripped]

- Any suffix is removed from the string.

[expr.literal.int.separators-stripped]

- Any underscores are removed from the string.

[expr.literal.int.u128-value]

- The string is converted to a `u128` value as if by `u128::from_str_radix` with the chosen radix. If the value does not fit in `u128`, it is a compiler error.

[expr.literal.int.cast]

- The `u128` value is converted to the expression’s type via a numeric cast.

> Note

> The final cast will truncate the value of the literal if it does not fit in the expression’s type. `rustc` includes a lint check named `overflowing_literals`, defaulting to `deny`, which rejects expressions where this occurs.

> Note

> `-1i8`, for example, is an application of the negation operator to the literal expression `1i8`, not a single integer literal expression. See Overflow for notes on representing the most negative value for a signed type.

[expr.literal.float]

## Floating-point literal expressions

[expr.literal.float.intro]

A floating-point literal expression has one of two forms:

- a single FLOAT_LITERAL token
- a single INTEGER_LITERAL token which has a suffix and no radix indicator

[expr.literal.float.suffix]

If the token has a suffix, the suffix must be the name of one of the primitive floating-point types: `f32` or `f64`, and the expression has that type.

[expr.literal.float.infer]

If the token has no suffix, the expression’s type is determined by type inference:

[expr.literal.float.inference-unique-type]

- If a floating-point type can be uniquely determined from the surrounding program context, the expression has that type.

[expr.literal.float.inference-default]

- If the program context under-constrains the type, it defaults to `f64`.

[expr.literal.float.inference-error]

- If the program context over-constrains the type, it is considered a static type error.

Examples of floating-point literal expressions:

    #![allow(unused)]
    fn main() {
    123.0f64;        // type f64
    0.1f64;          // type f64
    0.1f32;          // type f32
    12E+99_f64;      // type f64
    5f32;            // type f32
    let x: f64 = 2.; // type f64
    }

[expr.literal.float.result]

The value of the expression is determined from the string representation of the token as follows:

[expr.literal.float.type-suffix-stripped]

- Any suffix is removed from the string.

[expr.literal.float.separators-stripped]

- Any underscores are removed from the string.

[expr.literal.float.value]

- The string is converted to the expression’s type as if by `f32::from_str` or `f64::from_str`.

> Note

> `-1.0`, for example, is an application of the negation operator to the literal expression `1.0`, not a single floating-point literal expression.

> Note

> `inf` and `NaN` are not literal tokens. The `f32::INFINITY`, `f64::INFINITY`, `f32::NAN`, and `f64::NAN` constants can be used instead of literal expressions. In `rustc`, a literal large enough to be evaluated as infinite will trigger the `overflowing_literals` lint check.

[expr.literal.bool]

## Boolean literal expressions

[expr.literal.bool.intro]

A boolean literal expression consists of one of the keywords `true` or `false`.

[expr.literal.bool.result]

The expression’s type is the primitive boolean type, and its value is:

- true if the keyword is `true`
- false if the keyword is `false`

[expr.path]

# Path expressions

[expr.path.syntax]

Syntax
PathExpression →
PathInExpression
| QualifiedPathInExpression

[expr.path.intro]

A path used as an expression context denotes either a local variable or an item.

[expr.path.place]

Path expressions that resolve to local or static variables are place expressions; other paths are value expressions.

[expr.path.safety]

Using a `static mut` variable requires an `unsafe` block.

    #![allow(unused)]
    fn main() {
    mod globals {
        pub static STATIC_VAR: i32 = 5;
        pub static mut STATIC_MUT_VAR: i32 = 7;
    }
    let local_var = 3;
    local_var;
    globals::STATIC_VAR;
    unsafe { globals::STATIC_MUT_VAR };
    let some_constructor = Some::<i32>;
    let push_integer = Vec::<i32>::push;
    let slice_reverse = <[i32]>::reverse;
    }

[expr.path.const]

Evaluation of associated constants is handled the same way as `const` blocks.

[expr.block]

# Block expressions

[expr.block.syntax]

Syntax
BlockExpression →
{
InnerAttribute*
Statements?
}

Statements →
Statement+
| Statement+ ExpressionWithoutBlock
| ExpressionWithoutBlock

[expr.block.intro]

A block expression, or block, is a control flow expression and anonymous namespace scope for items and variable declarations.

[expr.block.sequential-evaluation]

As a control flow expression, a block sequentially executes its component non-item declaration statements and then its final optional expression.

[expr.block.namespace]

As an anonymous namespace scope, item declarations are only in scope inside the block itself and variables declared by `let` statements are in scope from the next statement until the end of the block. See the scopes chapter for more details.

[expr.block.inner-attributes]

The syntax for a block is `{`, then any inner attributes, then any number of statements, then an optional expression, called the final operand, and finally a `}`.

[expr.block.statements]

Statements are usually required to be followed by a semicolon, with two exceptions:

1. Item declaration statements do not need to be followed by a semicolon.
2. Expression statements usually require a following semicolon except if its outer expression is a flow control expression.

[expr.block.null-statement]

Furthermore, extra semicolons between statements are allowed, but these semicolons do not affect semantics.

[expr.block.evaluation]

When evaluating a block expression, each statement, except for item declaration statements, is executed sequentially.

[expr.block.result]

Then the final operand is executed, if given.

[expr.block.type]

The type of a block is the type of the final operand, or `()` if the final operand is omitted.

    #![allow(unused)]
    fn main() {
    fn fn_call() {}
    let _: () = {
        fn_call();
    };

    let five: i32 = {
        fn_call();
        5
    };

    assert_eq!(5, five);
    }

> Note

> As a control flow expression, if a block expression is the outer expression of an expression statement, the expected type is `()` unless it is followed immediately by a semicolon.

[expr.block.value]

Blocks are always value expressions and evaluate the last operand in value expression context.

> Note

> This can be used to force moving a value if really needed. For example, the following example fails on the call to `consume_self` because the struct was moved out of `s` in the block expression.

>     #![allow(unused)]
>     fn main() {
>     struct Struct;

>     impl Struct {
>         fn consume_self(self) {}
>         fn borrow_self(&self) {}
>     }

>     fn move_by_block_expression() {
>         let s = Struct;

>         // Move the value out of `s` in the block expression.
>         (&{ s }).borrow_self();

>         // Fails to execute because `s` is moved out of.
>         s.consume_self();
>     }
>     }

[expr.block.async]

## `async` blocks

[expr.block.async.syntax]

Syntax
AsyncBlockExpression → async move? BlockExpression

[expr.block.async.intro]

An async block is a variant of a block expression which evaluates to a future.

[expr.block.async.future-result]

The final expression of the block, if present, determines the result value of the future.

[expr.block.async.anonymous-type]

Executing an async block is similar to executing a closure expression: its immediate effect is to produce and return an anonymous type.

[expr.block.async.future]

Whereas closures return a type that implements one or more of the `std::ops::Fn` traits, however, the type returned for an async block implements the `std::future::Future` trait.

[expr.block.async.layout-unspecified]

The actual data format for this type is unspecified.

> Note

> The future type that rustc generates is roughly equivalent to an enum with one variant per `await` point, where each variant stores the data needed to resume from its corresponding point.

[expr.block.async.edition2018]

> 2018 Edition differences

> Async blocks are only available beginning with Rust 2018.

[expr.block.async.capture]

### Capture modes

Async blocks capture variables from their environment using the same capture modes as closures. Like closures, when written `async { .. }` the capture mode for each variable will be inferred from the content of the block. `async move { .. }` blocks however will move all referenced variables into the resulting future.

[expr.block.async.context]

### Async context

Because async blocks construct a future, they define an async context which can in turn contain `await` expressions. Async contexts are established by async blocks as well as the bodies of async functions, whose semantics are defined in terms of async blocks.

[expr.block.async.function]

### Control-flow operators

[expr.block.async.function.intro]

Async blocks act like a function boundary, much like closures.

[expr.block.async.function.return-try]

Therefore, the `?` operator and `return` expressions both affect the output of the future, not the enclosing function or other context. That is, `return <expr>` from within an async block will return the result of `<expr>` as the output of the future. Similarly, if `<expr>?` propagates an error, that error is propagated as the result of the future.

[expr.block.async.function.control-flow]

Finally, the `break` and `continue` keywords cannot be used to branch out from an async block. Therefore the following is illegal:

    #![allow(unused)]
    fn main() {
    loop {
        async move {
            break; // error[E0267]: `break` inside of an `async` block
        }
    }
    }

[expr.block.const]

## `const` blocks

[expr.block.const.syntax]

Syntax
ConstBlockExpression → const BlockExpression

[expr.block.const.intro]

A const block is a variant of a block expression whose body evaluates at compile-time instead of at runtime.

[expr.block.const.context]

Const blocks allows you to define a constant value without having to define new constant items, and thus they are also sometimes referred as inline consts. It also supports type inference so there is no need to specify the type, unlike constant items.

[expr.block.const.generic-params]

Const blocks have the ability to reference generic parameters in scope, unlike free constant items. They are desugared to constant items with generic parameters in scope (similar to associated constants, but without a trait or type they are associated with). For example, this code:

    #![allow(unused)]
    fn main() {
    fn foo<T>() -> usize {
        const { std::mem::size_of::<T>() + 1 }
    }
    }

is equivalent to:

    #![allow(unused)]
    fn main() {
    fn foo<T>() -> usize {
        {
            struct Const<T>(T);
            impl<T> Const<T> {
                const CONST: usize = std::mem::size_of::<T>() + 1;
            }
            Const::<T>::CONST
        }
    }
    }

[expr.block.const.evaluation]

If the const block expression is executed at runtime, then the constant is guaranteed to be evaluated, even if its return value is ignored:

    #![allow(unused)]
    fn main() {
    fn foo<T>() -> usize {
        // If this code ever gets executed, then the assertion has definitely
        // been evaluated at compile-time.
        const { assert!(std::mem::size_of::<T>() > 0); }
        // Here we can have unsafe code relying on the type being non-zero-sized.
        /* ... */
        42
    }
    }

[expr.block.const.not-executed]

If the const block expression is not executed at runtime, it may or may not be evaluated:

    #![allow(unused)]
    fn main() {
    if false {
        // The panic may or may not occur when the program is built.
        const { panic!(); }
    }
    }

[expr.block.unsafe]

## `unsafe` blocks

[expr.block.unsafe.syntax]

Syntax
UnsafeBlockExpression → unsafe BlockExpression

[expr.block.unsafe.intro]

See `unsafe` blocks for more information on when to use `unsafe`.

A block of code can be prefixed with the `unsafe` keyword to permit unsafe operations. Examples:

    #![allow(unused)]
    fn main() {
    unsafe {
        let b = [13u8, 17u8];
        let a = &b[0] as *const u8;
        assert_eq!(*a, 13);
        assert_eq!(*a.offset(1), 17);
    }

    unsafe fn an_unsafe_fn() -> i32 { 10 }
    let a = unsafe { an_unsafe_fn() };
    }

[expr.block.label]

## Labeled block expressions

Labeled block expressions are documented in the Loops and other breakable expressions section.

[expr.block.attributes]

## Attributes on block expressions

[expr.block.attributes.inner-attributes]

Inner attributes are allowed directly after the opening brace of a block expression in the following situations:

- Function and method bodies.
- Loop bodies (`loop`, `while`, and `for`).
- Block expressions used as a statement.
- Block expressions as elements of array expressions, tuple expressions, call expressions, and tuple-style struct expressions.
- A block expression as the tail expression of another block expression.

[expr.block.attributes.valid]

The attributes that have meaning on a block expression are `cfg` and the lint check attributes.

For example, this function returns `true` on unix platforms and `false` on other platforms.

    #![allow(unused)]
    fn main() {
    fn is_unix_platform() -> bool {
        #[cfg(unix)] { true }
        #[cfg(not(unix))] { false }
    }
    }

[expr.operator]

# Operator expressions

[expr.operator.syntax]

Syntax
OperatorExpression →
BorrowExpression
| DereferenceExpression
| TryPropagationExpression
| NegationExpression
| ArithmeticOrLogicalExpression
| ComparisonExpression
| LazyBooleanExpression
| TypeCastExpression
| AssignmentExpression
| CompoundAssignmentExpression

[expr.operator.intro]

Operators are defined for built in types by the Rust language.

[expr.operator.trait]

Many of the following operators can also be overloaded using traits in `std::ops` or `std::cmp`.

[expr.operator.int-overflow]

## Overflow

[expr.operator.int-overflow.intro]

Integer operators will panic when they overflow when compiled in debug mode. The `-C debug-assertions` and `-C overflow-checks` compiler flags can be used to control this more directly. The following things are considered to be overflow:

[expr.operator.int-overflow.binary-arith]

- When `+`, `*` or binary `-` create a value greater than the maximum value, or less than the minimum value that can be stored.

[expr.operator.int-overflow.unary-neg]

- Applying unary `-` to the most negative value of any signed integer type, unless the operand is a literal expression (or a literal expression standing alone inside one or more grouped expressions).

[expr.operator.int-overflow.div]

- Using `/` or `%`, where the left-hand argument is the smallest integer of a signed integer type and the right-hand argument is `-1`. These checks occur even when `-C overflow-checks` is disabled, for legacy reasons.

[expr.operator.int-overflow.shift]

- Using `<<` or `>>` where the right-hand argument is greater than or equal to the number of bits in the type of the left-hand argument, or is negative.

> Note

> The exception for literal expressions behind unary `-` means that forms such as `-128_i8` or `let j: i8 = -(128)` never cause a panic and have the expected value of -128.

> In these cases, the literal expression already has the most negative value for its type (for example, `128_i8` has the value -128) because integer literals are truncated to their type per the description in Integer literal expressions.

> Negation of these most negative values leaves the value unchanged due to two’s complement overflow conventions.

> In `rustc`, these most negative expressions are also ignored by the `overflowing_literals` lint check.

[expr.operator.borrow]

## Borrow operators

[expr.operator.borrow.syntax]

Syntax
BorrowExpression →
( & | && ) Expression
| ( & | && ) mut Expression
| ( & | && ) raw const Expression
| ( & | && ) raw mut Expression

[expr.operator.borrow.intro]

The `&` (shared borrow) and `&mut` (mutable borrow) operators are unary prefix operators.

[expr.operator.borrow.result]

When applied to a place expression, this expressions produces a reference (pointer) to the location that the value refers to.

[expr.operator.borrow.lifetime]

The memory location is also placed into a borrowed state for the duration of the reference. For a shared borrow (`&`), this implies that the place may not be mutated, but it may be read or shared again. For a mutable borrow (`&mut`), the place may not be accessed in any way until the borrow expires.

[expr.operator.borrow.mut]

`&mut` evaluates its operand in a mutable place expression context.

[expr.operator.borrow.temporary]

If the `&` or `&mut` operators are applied to a value expression, then a temporary value is created.

These operators cannot be overloaded.

    #![allow(unused)]
    fn main() {
    {
        // a temporary with value 7 is created that lasts for this scope.
        let shared_reference = &7;
    }
    let mut array = [-2, 3, 9];
    {
        // Mutably borrows `array` for this scope.
        // `array` may only be used through `mutable_reference`.
        let mutable_reference = &mut array;
    }
    }

[expr.borrow.and-and-syntax]

Even though `&&` is a single token (the lazy ‘and’ operator), when used in the context of borrow expressions it works as two borrows:

    #![allow(unused)]
    fn main() {
    // same meanings:
    let a = &&  10;
    let a = & & 10;

    // same meanings:
    let a = &&&&  mut 10;
    let a = && && mut 10;
    let a = & & & & mut 10;
    }

[expr.borrow.raw]

### Raw borrow operators

[expr.borrow.raw.intro]

`&raw const` and `&raw mut` are the raw borrow operators.

[expr.borrow.raw.place]

The operand expression of these operators is evaluated in place expression context.

[expr.borrow.raw.result]

`&raw const expr` then creates a const raw pointer of type `*const T` to the given place, and `&raw mut expr` creates a mutable raw pointer of type `*mut T`.

[expr.borrow.raw.invalid-ref]

The raw borrow operators must be used instead of a borrow operator whenever the place expression could evaluate to a place that is not properly aligned or does not store a valid value as determined by its type, or whenever creating a reference would introduce incorrect aliasing assumptions. In those situations, using a borrow operator would cause undefined behavior by creating an invalid reference, but a raw pointer may still be constructed.

The following is an example of creating a raw pointer to an unaligned place through a `packed` struct:

    #![allow(unused)]
    fn main() {
    #[repr(packed)]
    struct Packed {
        f1: u8,
        f2: u16,
    }

    let packed = Packed { f1: 1, f2: 2 };
    // `&packed.f2` would create an unaligned reference, and thus be undefined behavior!
    let raw_f2 = &raw const packed.f2;
    assert_eq!(unsafe { raw_f2.read_unaligned() }, 2);
    }

The following is an example of creating a raw pointer to a place that does not contain a valid value:

    #![allow(unused)]
    fn main() {
    use std::mem::MaybeUninit;

    struct Demo {
        field: bool,
    }

    let mut uninit = MaybeUninit::<Demo>::uninit();
    // `&uninit.as_mut().field` would create a reference to an uninitialized `bool`,
    // and thus be undefined behavior!
    let f1_ptr = unsafe { &raw mut (*uninit.as_mut_ptr()).field };
    unsafe { f1_ptr.write(true); }
    let init = unsafe { uninit.assume_init() };
    }

[expr.deref]

## The dereference operator

[expr.deref.syntax]

Syntax
DereferenceExpression → * Expression

[expr.deref.intro]

The `*` (dereference) operator is also a unary prefix operator.

[expr.deref.result]

When applied to a pointer it denotes the pointed-to location.

[expr.deref.mut]

If the expression is of type `&mut T` or `*mut T`, and is either a local variable, a (nested) field of a local variable or is a mutable place expression, then the resulting memory location can be assigned to.

[expr.deref.safety]

Dereferencing a raw pointer requires `unsafe`.

[expr.deref.traits]

On non-pointer types `*x` is equivalent to `*std::ops::Deref::deref(&x)` in an immutable place expression context and `*std::ops::DerefMut::deref_mut(&mut x)` in a mutable place expression context.

    #![allow(unused)]
    fn main() {
    let x = &7;
    assert_eq!(*x, 7);
    let y = &mut 9;
    *y = 11;
    assert_eq!(*y, 11);
    }

[expr.try]

## The try propagation expression

[expr.try.syntax]

Syntax
TryPropagationExpression → Expression ?

[expr.try.intro]

The try propagation expression uses the value of the inner expression and the `Try` trait to decide whether to produce a value, and if so, what value to produce, or whether to return a value to the caller, and if so, what value to return.

> Example

>     #![allow(unused)]
>     fn main() {
>     use std::num::ParseIntError;
>     fn try_to_parse() -> Result<i32, ParseIntError> {
>         let x: i32 = "123".parse()?; // `x` is `123`.
>         let y: i32 = "24a".parse()?; // Returns an `Err()` immediately.
>         Ok(x + y)                    // Doesn't run.
>     }

>     let res = try_to_parse();
>     println!("{res:?}");
>     assert!(res.is_err())
>     }

>     #![allow(unused)]
>     fn main() {
>     fn try_option_some() -> Option<u8> {
>         let val = Some(1)?;
>         Some(val)
>     }
>     assert_eq!(try_option_some(), Some(1));

>     fn try_option_none() -> Option<u8> {
>         let val = None?;
>         Some(val)
>     }
>     assert_eq!(try_option_none(), None);
>     }

>     use std::ops::ControlFlow;

>     pub struct TreeNode<T> {
>         value: T,
>         left: Option<Box<TreeNode<T>>>,
>         right: Option<Box<TreeNode<T>>>,
>     }

>     impl<T> TreeNode<T> {
>         pub fn traverse_inorder<B>(&self, f: &mut impl FnMut(&T) -> ControlFlow<B>) -> ControlFlow<B> {
>             if let Some(left) = &self.left {
>                 left.traverse_inorder(f)?;
>             }
>             f(&self.value)?;
>             if let Some(right) = &self.right {
>                 right.traverse_inorder(f)?;
>             }
>             ControlFlow::Continue(())
>         }
>     }

>     fn main() {
>         let n = TreeNode {
>             value: 1,
>             left: Some(Box::new(TreeNode{value: 2, left: None, right: None})),
>             right: None,
>         };
>         let v = n.traverse_inorder(&mut |t| {
>             if *t == 2 {
>                 ControlFlow::Break("found")
>             } else {
>                 ControlFlow::Continue(())
>             }
>         });
>         assert_eq!(v, ControlFlow::Break("found"));
>     }

> Note

> The `Try` trait is currently unstable, and thus cannot be implemented for user types.

> The try propagation expression is currently roughly equivalent to:

>     #![allow(unused)]
>     fn main() {
>     #![ feature(try_trait_v2) ]
>     fn example() -> Result<(), ()> {
>     let expr = Ok(());
>     match core::ops::Try::branch(expr) {
>         core::ops::ControlFlow::Continue(val) => val,
>         core::ops::ControlFlow::Break(residual) =>
>             return core::ops::FromResidual::from_residual(residual),
>     }
>     Ok(())
>     }
>     }

> Note

> The try propagation operator is sometimes called the question mark operator, the `?` operator, or the try operator.

[expr.try.restricted-types]

The try propagation operator can be applied to expressions with the type of:

- `Result<T, E>`
  - `Result::Ok(val)` evaluates to `val`.
  - `Result::Err(e)` returns `Result::Err(From::from(e))`.
- `Option<T>`
  - `Option::Some(val)` evaluates to `val`.
  - `Option::None` returns `Option::None`.
- `ControlFlow<B, C>`
  - `ControlFlow::Continue(c)` evaluates to `c`.
  - `ControlFlow::Break(b)` returns `ControlFlow::Break(b)`.
- `Poll<Result<T, E>>`
  - `Poll::Ready(Ok(val))` evaluates to `Poll::Ready(val)`.
  - `Poll::Ready(Err(e))` returns `Poll::Ready(Err(From::from(e)))`.
  - `Poll::Pending` evaluates to `Poll::Pending`.
- `Poll<Option<Result<T, E>>>`
  - `Poll::Ready(Some(Ok(val)))` evaluates to `Poll::Ready(Some(val))`.
  - `Poll::Ready(Some(Err(e)))` returns `Poll::Ready(Some(Err(From::from(e))))`.
  - `Poll::Ready(None)` evaluates to `Poll::Ready(None)`.
  - `Poll::Pending` evaluates to `Poll::Pending`.

[expr.negate]

## Negation operators

[expr.negate.syntax]

Syntax
NegationExpression →
- Expression
| ! Expression

[expr.negate.intro]

These are the last two unary operators.

[expr.negate.results]

This table summarizes the behavior of them on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two’s complement. The operands of all of these operators are evaluated in value expression context so are moved or copied.

Symbol | Integer | `bool` | Floating Point | Overloading Trait
--- | --- | --- | --- | ---
`-` | Negation* |  | Negation | `std::ops::Neg`
`!` | Bitwise NOT | Logical NOT |  | `std::ops::Not`

* Only for signed integer types.

Here are some example of these operators

    #![allow(unused)]
    fn main() {
    let x = 6;
    assert_eq!(-x, -6);
    assert_eq!(!x, -7);
    assert_eq!(true, !false);
    }

[expr.arith-logic]

## Arithmetic and logical binary operators

[expr.arith-logic.syntax]

Syntax
ArithmeticOrLogicalExpression →
Expression + Expression
| Expression - Expression
| Expression * Expression
| Expression / Expression
| Expression % Expression
| Expression & Expression
| Expression | Expression
| Expression ^ Expression
| Expression << Expression
| Expression >> Expression

[expr.arith-logic.intro]

Binary operators expressions are all written with infix notation.

[expr.arith-logic.behavior]

This table summarizes the behavior of arithmetic and logical binary operators on primitive types and which traits are used to overload these operators for other types. Remember that signed integers are always represented using two’s complement. The operands of all of these operators are evaluated in value expression context so are moved or copied.

Symbol | Integer | `bool` | Floating Point | Overloading Trait | Overloading Compound Assignment Trait
--- | --- | --- | --- | --- | ---
`+` | Addition |  | Addition | `std::ops::Add` | `std::ops::AddAssign`
`-` | Subtraction |  | Subtraction | `std::ops::Sub` | `std::ops::SubAssign`
`*` | Multiplication |  | Multiplication | `std::ops::Mul` | `std::ops::MulAssign`
`/` | Division*† |  | Division | `std::ops::Div` | `std::ops::DivAssign`
`%` | Remainder**† |  | Remainder | `std::ops::Rem` | `std::ops::RemAssign`
`&` | Bitwise AND | Logical AND |  | `std::ops::BitAnd` | `std::ops::BitAndAssign`
`|` | Bitwise OR | Logical OR |  | `std::ops::BitOr` | `std::ops::BitOrAssign`
`^` | Bitwise XOR | Logical XOR |  | `std::ops::BitXor` | `std::ops::BitXorAssign`
`<<` | Left Shift |  |  | `std::ops::Shl` | `std::ops::ShlAssign`
`>>` | Right Shift*** |  |  | `std::ops::Shr` | `std::ops::ShrAssign`

* Integer division rounds towards zero.

** Rust uses a remainder defined with truncating division. Given `remainder = dividend % divisor`, the remainder will have the same sign as the dividend.

*** Arithmetic right shift on signed integer types, logical right shift on unsigned integer types.

† For integer types, division by zero panics.

Here are examples of these operators being used.

    #![allow(unused)]
    fn main() {
    assert_eq!(3 + 6, 9);
    assert_eq!(5.5 - 1.25, 4.25);
    assert_eq!(-5 * 14, -70);
    assert_eq!(14 / 3, 4);
    assert_eq!(100 % 7, 2);
    assert_eq!(0b1010 & 0b1100, 0b1000);
    assert_eq!(0b1010 | 0b1100, 0b1110);
    assert_eq!(0b1010 ^ 0b1100, 0b110);
    assert_eq!(13 << 3, 104);
    assert_eq!(-10 >> 2, -3);
    }

[expr.cmp]

## Comparison operators

[expr.cmp.syntax]

Syntax
ComparisonExpression →
Expression == Expression
| Expression != Expression
| Expression > Expression
| Expression < Expression
| Expression >= Expression
| Expression <= Expression

[expr.cmp.intro]

Comparison operators are also defined both for primitive types and many types in the standard library.

[expr.cmp.paren-chaining]

Parentheses are required when chaining comparison operators. For example, the expression `a == b == c` is invalid and may be written as `(a == b) == c`.

[expr.cmp.trait]

Unlike arithmetic and logical operators, the traits for overloading these operators are used more generally to show how a type may be compared and will likely be assumed to define actual comparisons by functions that use these traits as bounds. Many functions and macros in the standard library can then use that assumption (although not to ensure safety).

[expr.cmp.place]

Unlike the arithmetic and logical operators above, these operators implicitly take shared borrows of their operands, evaluating them in place expression context:

    #![allow(unused)]
    fn main() {
    let a = 1;
    let b = 1;
    a == b;
    // is equivalent to
    ::std::cmp::PartialEq::eq(&a, &b);
    }

This means that the operands don’t have to be moved out of.

[expr.cmp.behavior]

Symbol | Meaning | Overloading method
--- | --- | ---
`==` | Equal | `std::cmp::PartialEq::eq`
`!=` | Not equal | `std::cmp::PartialEq::ne`
`>` | Greater than | `std::cmp::PartialOrd::gt`
`<` | Less than | `std::cmp::PartialOrd::lt`
`>=` | Greater than or equal to | `std::cmp::PartialOrd::ge`
`<=` | Less than or equal to | `std::cmp::PartialOrd::le`

Here are examples of the comparison operators being used.

    #![allow(unused)]
    fn main() {
    assert!(123 == 123);
    assert!(23 != -12);
    assert!(12.5 > 12.2);
    assert!([1, 2, 3] < [1, 3, 4]);
    assert!('A' <= 'B');
    assert!("World" >= "Hello");
    }

[expr.bool-logic]

## Lazy boolean operators

[expr.bool-logic.syntax]

Syntax
LazyBooleanExpression →
Expression || Expression
| Expression && Expression

[expr.bool-logic.intro]

The operators `||` and `&&` may be applied to operands of boolean type. The `||` operator denotes logical ‘or’, and the `&&` operator denotes logical ‘and’.

[expr.bool-logic.conditional-evaluation]

They differ from `|` and `&` in that the right-hand operand is only evaluated when the left-hand operand does not already determine the result of the expression. That is, `||` only evaluates its right-hand operand when the left-hand operand evaluates to `false`, and `&&` only when it evaluates to `true`.

    #![allow(unused)]
    fn main() {
    let x = false || true; // true
    let y = false && panic!(); // false, doesn't evaluate `panic!()`
    }

[expr.as]

## Type cast expressions

[expr.as.syntax]

Syntax
TypeCastExpression → Expression as TypeNoBounds

[expr.as.intro]

A type cast expression is denoted with the binary operator `as`.

[expr.as.result]

Executing an `as` expression casts the value on the left-hand side to the type on the right-hand side.

An example of an `as` expression:

    #![allow(unused)]
    fn main() {
    fn sum(values: &[f64]) -> f64 { 0.0 }
    fn len(values: &[f64]) -> i32 { 0 }
    fn average(values: &[f64]) -> f64 {
        let sum: f64 = sum(values);
        let size: f64 = len(values) as f64;
        sum / size
    }
    }

[expr.as.coercions]

`as` can be used to explicitly perform coercions, as well as the following additional casts. Any cast that does not fit either a coercion rule or an entry in the table is a compiler error. Here `*T` means either `*const T` or `*mut T`. `m` stands for optional `mut` in reference types and `mut` or `const` in pointer types.

Type of `e` | `U` | Cast performed by `e as U`
--- | --- | ---
Integer or Float type | Integer or Float type | Numeric cast
Enumeration | Integer type | Enum cast
`bool` or `char` | Integer type | Primitive to integer cast
`u8` | `char` | `u8` to `char` cast
`*T` | `*V` 1 | Pointer to pointer cast
`*T` where `T: Sized` | Integer type | Pointer to address cast
Integer type | `*V` where `V: Sized` | Address to pointer cast
`&m₁ [T; n]` | `*m₂ T` 2 | Array to pointer cast
`*m₁ [T; n]` | `*m₂ T` 2 | Array to pointer cast
Function item | Function pointer | Function item to function pointer cast
Function item | `*V` where `V: Sized` | Function item to pointer cast
Function item | Integer | Function item to address cast
Function pointer | `*V` where `V: Sized` | Function pointer to pointer cast
Function pointer | Integer | Function pointer to address cast
Closure 3 | Function pointer | Closure to function pointer cast

### Semantics

[expr.as.numeric]

#### Numeric cast

[expr.as.numeric.int-same-size]

- Casting between two integers of the same size (e.g. i32 -> u32) is a no-op (Rust uses 2’s complement for negative values of fixed integers)

      #![allow(unused)]
      fn main() {
      assert_eq!(42i8 as u8, 42u8);
      assert_eq!(-1i8 as u8, 255u8);
      assert_eq!(255u8 as i8, -1i8);
      assert_eq!(-1i16 as u16, 65535u16);
      }

[expr.as.numeric.int-truncation]

- Casting from a larger integer to a smaller integer (e.g. u32 -> u8) will truncate

      #![allow(unused)]
      fn main() {
      assert_eq!(42u16 as u8, 42u8);
      assert_eq!(1234u16 as u8, 210u8);
      assert_eq!(0xabcdu16 as u8, 0xcdu8);

      assert_eq!(-42i16 as i8, -42i8);
      assert_eq!(1234u16 as i8, -46i8);
      assert_eq!(0xabcdi32 as i8, -51i8);
      }

[expr.as.numeric.int-extension]

- Casting from a smaller integer to a larger integer (e.g. u8 -> u32) will

  - zero-extend if the source is unsigned
  - sign-extend if the source is signed

      #![allow(unused)]
      fn main() {
      assert_eq!(42i8 as i16, 42i16);
      assert_eq!(-17i8 as i16, -17i16);
      assert_eq!(0b1000_1010u8 as u16, 0b0000_0000_1000_1010u16, "Zero-extend");
      assert_eq!(0b0000_1010i8 as i16, 0b0000_0000_0000_1010i16, "Sign-extend 0");
      assert_eq!(0b1000_1010u8 as i8 as i16, 0b1111_1111_1000_1010u16 as i16, "Sign-extend 1");
      }

[expr.as.numeric.float-as-int]

- Casting from a float to an integer will round the float towards zero

  - `NaN` will return `0`
  - Values larger than the maximum integer value, including `INFINITY`, will saturate to the maximum value of the integer type.
  - Values smaller than the minimum integer value, including `NEG_INFINITY`, will saturate to the minimum value of the integer type.

      #![allow(unused)]
      fn main() {
      assert_eq!(42.9f32 as i32, 42);
      assert_eq!(-42.9f32 as i32, -42);
      assert_eq!(42_000_000f32 as i32, 42_000_000);
      assert_eq!(std::f32::NAN as i32, 0);
      assert_eq!(1_000_000_000_000_000f32 as i32, 0x7fffffffi32);
      assert_eq!(std::f32::NEG_INFINITY as i32, -0x80000000i32);
      }

[expr.as.numeric.int-as-float]

- Casting from an integer to float will produce the closest possible float *

  - if necessary, rounding is according to `roundTiesToEven` mode ***
  - on overflow, infinity (of the same sign as the input) is produced
  - note: with the current set of numeric types, overflow can only happen on `u128 as f32` for values greater or equal to `f32::MAX + (0.5 ULP)`

      #![allow(unused)]
      fn main() {
      assert_eq!(1337i32 as f32, 1337f32);
      assert_eq!(123_456_789i32 as f32, 123_456_790f32, "Rounded");
      assert_eq!(0xffffffff_ffffffff_ffffffff_ffffffff_u128 as f32, std::f32::INFINITY);
      }

[expr.as.numeric.float-widening]

- Casting from an f32 to an f64 is perfect and lossless

      #![allow(unused)]
      fn main() {
      assert_eq!(1_234.5f32 as f64, 1_234.5f64);
      assert_eq!(std::f32::INFINITY as f64, std::f64::INFINITY);
      assert!((std::f32::NAN as f64).is_nan());
      }

[expr.as.numeric.float-narrowing]

- Casting from an f64 to an f32 will produce the closest possible f32 **

  - if necessary, rounding is according to `roundTiesToEven` mode ***
  - on overflow, infinity (of the same sign as the input) is produced

      #![allow(unused)]
      fn main() {
      assert_eq!(1_234.5f64 as f32, 1_234.5f32);
      assert_eq!(1_234_567_891.123f64 as f32, 1_234_567_890f32, "Rounded");
      assert_eq!(std::f64::INFINITY as f32, std::f32::INFINITY);
      assert!((std::f64::NAN as f32).is_nan());
      }

* if integer-to-float casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected.

** if f64-to-f32 casts with this rounding mode and overflow behavior are not supported natively by the hardware, these casts will likely be slower than expected.

*** as defined in IEEE 754-2008 §4.3.1: pick the nearest floating point number, preferring the one with an even least significant digit if exactly halfway between two floating point numbers.

[expr.as.enum]

#### Enum cast

[expr.as.enum.discriminant]

Casts an enum to its discriminant, then uses a numeric cast if needed. Casting is limited to the following kinds of enumerations:

- Unit-only enums
- Field-less enums without explicit discriminants, or where only unit-variants have explicit discriminants

    #![allow(unused)]
    fn main() {
    enum Enum { A, B, C }
    assert_eq!(Enum::A as i32, 0);
    assert_eq!(Enum::B as i32, 1);
    assert_eq!(Enum::C as i32, 2);
    }

[expr.as.enum.no-drop]

Casting is not allowed if the enum implements `Drop`.

[expr.as.bool-char-as-int]

#### Primitive to integer cast

- `false` casts to `0`, `true` casts to `1`
- `char` casts to the value of the code point, then uses a numeric cast if needed.

    #![allow(unused)]
    fn main() {
    assert_eq!(false as i32, 0);
    assert_eq!(true as i32, 1);
    assert_eq!('A' as i32, 65);
    assert_eq!('Ö' as i32, 214);
    }

[expr.as.u8-as-char]

#### `u8` to `char` cast

Casts to the `char` with the corresponding code point.

    #![allow(unused)]
    fn main() {
    assert_eq!(65u8 as char, 'A');
    assert_eq!(214u8 as char, 'Ö');
    }

[expr.as.pointer-as-int]

#### Pointer to address cast

Casting from a raw pointer to an integer produces the machine address of the referenced memory. If the integer type is smaller than the pointer type, the address may be truncated; using `usize` avoids this.

[expr.as.int-as-pointer]

#### Address to pointer cast

Casting from an integer to a raw pointer interprets the integer as a memory address and produces a pointer referencing that memory.

> Warning

> This interacts with the Rust memory model, which is still under development. A pointer obtained from this cast may suffer additional restrictions even if it is bitwise equal to a valid pointer. Dereferencing such a pointer may be undefined behavior if aliasing rules are not followed.

A trivial example of sound address arithmetic:

    #![allow(unused)]
    fn main() {
    let mut values: [i32; 2] = [1, 2];
    let p1: *mut i32 = values.as_mut_ptr();
    let first_address = p1 as usize;
    let second_address = first_address + 4; // 4 == size_of::<i32>()
    let p2 = second_address as *mut i32;
    unsafe {
        *p2 += 1;
    }
    assert_eq!(values[1], 3);
    }

[expr.as.pointer]

#### Pointer-to-pointer cast

[expr.as.pointer.behavior]

`*const T` / `*mut T` can be cast to `*const U` / `*mut U` with the following behavior:

[expr.as.pointer.sized]

- If `T` and `U` are both sized, the pointer is returned unchanged.

[expr.as.pointer.unsized]

- If `T` and `U` are both unsized, the pointer is also returned unchanged. In particular, the metadata is preserved exactly.

  For instance, a cast from `*const [T]` to `*const [U]` preserves the number of elements. Note that, as a consequence, such casts do not necessarily preserve the size of the pointer’s referent (e.g., casting `*const [u16]` to `*const [u8]` will result in a raw pointer which refers to an object of half the size of the original). The same holds for `str` and any compound type whose unsized tail is a slice type, such as `struct Foo(i32, [u8])` or `(u64, Foo)`.

[expr.as.pointer.discard-metadata]

- If `T` is unsized and `U` is sized, the cast discards all metadata that completes the wide pointer `T` and produces a thin pointer `U` consisting of the data part of the unsized pointer.

[expr.assign]

## Assignment expressions

[expr.assign.syntax]

Syntax
AssignmentExpression → Expression = Expression

[expr.assign.intro]

An assignment expression moves a value into a specified place.

[expr.assign.assignee]

An assignment expression consists of a mutable assignee expression, the assignee operand, followed by an equals sign (`=`) and a value expression, the assigned value operand.

[expr.assign.behavior-basic]

In its most basic form, an assignee expression is a place expression, and we discuss this case first.

[expr.assign.behavior-destructuring]

The more general case of destructuring assignment is discussed below, but this case always decomposes into sequential assignments to place expressions, which may be considered the more fundamental case.

[expr.assign.basic]

### Basic assignments

[expr.assign.evaluation-order]

Evaluating assignment expressions begins by evaluating its operands. The assigned value operand is evaluated first, followed by the assignee expression.

[expr.assign.destructuring-order]

For destructuring assignment, subexpressions of the assignee expression are evaluated left-to-right.

> Note

> This is different than other expressions in that the right operand is evaluated before the left one.

[expr.assign.drop-target]

It then has the effect of first dropping the value at the assigned place, unless the place is an uninitialized local variable or an uninitialized field of a local variable.

[expr.assign.behavior]

Next it either copies or moves the assigned value to the assigned place.

[expr.assign.result]

An assignment expression always produces the unit value.

Example:

    #![allow(unused)]
    fn main() {
    let mut x = 0;
    let y = 0;
    x = y;
    }

[expr.assign.destructure]

### Destructuring assignments

[expr.assign.destructure.intro]

Destructuring assignment is a counterpart to destructuring pattern matches for variable declaration, permitting assignment to complex values, such as tuples or structs. For instance, we may swap two mutable variables:

    #![allow(unused)]
    fn main() {
    let (mut a, mut b) = (0, 1);
    // Swap `a` and `b` using destructuring assignment.
    (b, a) = (a, b);
    }

[expr.assign.destructure.assignee]

In contrast to destructuring declarations using `let`, patterns may not appear on the left-hand side of an assignment due to syntactic ambiguities. Instead, a group of expressions that correspond to patterns are designated to be assignee expressions, and permitted on the left-hand side of an assignment. Assignee expressions are then desugared to pattern matches followed by sequential assignment.

[expr.assign.destructure.irrefutable]

The desugared patterns must be irrefutable: in particular, this means that only slice patterns whose length is known at compile-time, and the trivial slice `[..]`, are permitted for destructuring assignment.

The desugaring method is straightforward, and is illustrated best by example.

    #![allow(unused)]
    fn main() {
    struct Struct { x: u32, y: u32 }
    let (mut a, mut b) = (0, 0);
    (a, b) = (3, 4);

    [a, b] = [3, 4];

    Struct { x: a, y: b } = Struct { x: 3, y: 4};

    // desugars to:

    {
        let (_a, _b) = (3, 4);
        a = _a;
        b = _b;
    }

    {
        let [_a, _b] = [3, 4];
        a = _a;
        b = _b;
    }

    {
        let Struct { x: _a, y: _b } = Struct { x: 3, y: 4};
        a = _a;
        b = _b;
    }
    }

[expr.assign.destructure.repeat-ident]

Identifiers are not forbidden from being used multiple times in a single assignee expression.

[expr.assign.destructure.discard-value]

Underscore expressions and empty range expressions may be used to ignore certain values, without binding them.

[expr.assign.destructure.default-binding]

Note that default binding modes do not apply for the desugared expression.

[expr.assign.destructure.tmp-scopes]

> Note

> The desugaring restricts the temporary scope of the assigned value operand (the RHS) of a destructuring assignment.

> In a basic assignment, the temporary is dropped at the end of the enclosing temporary scope. Below, that’s the statement. Therefore, the assignment and use is allowed.

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     fn f<T>(x: T) -> T { x }
>     let x;
>     (x = f(&temp()), x); // OK
>     }

> Conversely, in a destructuring assignment, the temporary is dropped at the end of the `let` statement in the desugaring. As that happens before we try to assign to `x`, below, it fails.

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     fn f<T>(x: T) -> T { x }
>     let x;
>     [x] = [f(&temp())]; // ERROR
>     }

> This desugars to:

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     fn f<T>(x: T) -> T { x }
>     let x;
>     {
>         let [_x] = [f(&temp())];
>         //                     ^
>         //      The temporary is dropped here.
>         x = _x; // ERROR
>     }
>     }

[expr.assign.destructure.tmp-ext]

> Note

> Due to the desugaring, the assigned value operand (the RHS) of a destructuring assignment is an extending expression within a newly-introduced block.

> Below, because the temporary scope is extended to the end of this introduced block, the assignment is allowed.

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     let x;
>     [x] = [&temp()]; // OK
>     }

> This desugars to:

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     let x;
>     { let [_x] = [&temp()]; x = _x; } // OK
>     }

> However, if we try to use `x`, even within the same statement, we’ll get an error because the temporary is dropped at the end of this introduced block.

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     let x;
>     ([x] = [&temp()], x); // ERROR
>     }

> This desugars to:

>     #![allow(unused)]
>     fn main() {
>     fn temp() {}
>     let x;
>     (
>         {
>             let [_x] = [&temp()];
>             x = _x;
>         }, // <-- The temporary is dropped here.
>         x, // ERROR
>     );
>     }

[expr.compound-assign]

## Compound assignment expressions

[expr.compound-assign.syntax]

Syntax
CompoundAssignmentExpression →
Expression += Expression
| Expression -= Expression
| Expression *= Expression
| Expression /= Expression
| Expression %= Expression
| Expression &= Expression
| Expression |= Expression
| Expression ^= Expression
| Expression <<= Expression
| Expression >>= Expression

[expr.compound-assign.intro]

Compound assignment expressions combine arithmetic and logical binary operators with assignment expressions.

For example:

    #![allow(unused)]
    fn main() {
    let mut x = 5;
    x += 1;
    assert!(x == 6);
    }

The syntax of compound assignment is a mutable place expression, the assigned operand, then one of the operators followed by an `=` as a single token (no whitespace), and then a value expression, the modifying operand.

[expr.compound-assign.place]

Unlike other place operands, the assigned place operand must be a place expression.

[expr.compound-assign.no-value]

Attempting to use a value expression is a compiler error rather than promoting it to a temporary.

[expr.compound-assign.operand-order]

Evaluation of compound assignment expressions depends on the types of the operands.

[expr.compound-assign.primitives]

If the types of both operands are known, prior to monomorphization, to be primitive, the right hand side is evaluated first, the left hand side is evaluated next, and the place given by the evaluation of the left hand side is mutated by applying the operator to the values of both sides.

    use core::{num::Wrapping, ops::AddAssign};

    trait Equate {}
    impl<T> Equate for (T, T) {}

    fn f1(x: (u8,)) {
        let mut order = vec![];
        // The RHS is evaluated first as both operands are of primitive
        // type.
        { order.push(2); x }.0 += { order.push(1); x }.0;
        assert!(order.is_sorted());
    }

    fn f2(x: (Wrapping<u8>,)) {
        let mut order = vec![];
        // The LHS is evaluated first as `Wrapping<_>` is not a primitive
        // type.
        { order.push(1); x }.0 += { order.push(2); (0u8,) }.0;
        assert!(order.is_sorted());
    }

    fn f3<T: AddAssign<u8> + Copy>(x: (T,)) where (T, u8): Equate {
        let mut order = vec![];
        // The LHS is evaluated first as one of the operands is a generic
        // parameter, even though that generic parameter can be unified
        // with a primitive type due to the where clause bound.
        { order.push(1); x }.0 += { order.push(2); (0u8,) }.0;
        assert!(order.is_sorted());
    }

    fn main() {
        f1((0u8,));
        f2((Wrapping(0u8),));
        // We supply a primitive type as the generic argument, but this
        // does not affect the evaluation order in `f3` when
        // monomorphized.
        f3::<u8>((0u8,));
    }

> Note

> This is unusual. Elsewhere left to right evaluation is the norm.

> See the eval order test for more examples.

[expr.compound-assign.trait]

Otherwise, this expression is syntactic sugar for using the corresponding trait for the operator (see expr.arith-logic.behavior) and calling its method with the left hand side as the receiver and the right hand side as the next argument.

For example, the following two statements are equivalent:

    #![allow(unused)]
    fn main() {
    use std::ops::AddAssign;
    fn f<T: AddAssign + Copy>(mut x: T, y: T) {
        x += y; // Statement 1.
        x.add_assign(y); // Statement 2.
    }
    }

> Note

> Surprisingly, desugaring this further to a fully qualified method call is not equivalent, as there is special borrow checker behavior when the mutable reference to the first operand is taken via autoref.

>     #![allow(unused)]
>     fn main() {
>     use std::ops::AddAssign;
>     fn f<T: AddAssign + Copy>(mut x: T) {
>         // Here we used `x` as both the LHS and the RHS. Because the
>         // mutable borrow of the LHS needed to call the trait method
>         // is taken implicitly by autoref, this is OK.
>         x += x; //~ OK
>         x.add_assign(x); //~ OK
>     }
>     }

>     #![allow(unused)]
>     fn main() {
>     use std::ops::AddAssign;
>     fn f<T: AddAssign + Copy>(mut x: T) {
>         // We can't desugar the above to the below, as once we take the
>         // mutable borrow of `x` to pass the first argument, we can't
>         // pass `x` by value in the second argument because the mutable
>         // reference is still live.
>         <T as AddAssign>::add_assign(&mut x, x);
>         //~^ ERROR cannot use `x` because it was mutably borrowed
>     }
>     }

>     #![allow(unused)]
>     fn main() {
>     use std::ops::AddAssign;
>     fn f<T: AddAssign + Copy>(mut x: T) {
>         // As above.
>         (&mut x).add_assign(x);
>         //~^ ERROR cannot use `x` because it was mutably borrowed
>     }
>     }

[expr.compound-assign.result]

As with normal assignment expressions, compound assignment expressions always produce the unit value.

> Warning

> Avoid writing code that depends on the evaluation order of operands in compound assignments as it can be unusual and surprising.

1. Where `T` and `V` have compatible metadata:

   - `V: Sized`, or
   - Both slice metadata (`*[u16]` -> `*[u8]`, `*str` -> `*(u8, [u32])`), or
   - Both the same trait object metadata, modulo dropping auto traits (`*dyn Debug` -> `*(u16, dyn Debug)`, `*dyn Debug + Send` -> `*dyn Debug`)
     - Note: adding auto traits is only allowed if the principal trait has the auto trait as a super trait (given `trait T: Send {}`, `*dyn T` -> `*dyn T + Send` is valid, but `*dyn Debug` -> `*dyn Debug + Send` is not)
     - Note: Generics (including lifetimes) must match (`*dyn T<'a, A>` -> `*dyn T<'b, B>` requires `'a = 'b` and `A = B`)
   ↩

2. Only when `m₁` is `mut` or `m₂` is `const`. Casting `mut` reference/pointer to `const` pointer is allowed. ↩ ↩2

3. Only closures that do not capture (close over) any local variables can be cast to function pointers. ↩

[expr.paren]

# Grouped expressions

[expr.paren.syntax]

Syntax
GroupedExpression → ( Expression )

[expr.paren.intro]

A parenthesized expression wraps a single expression, evaluating to that expression. The syntax for a parenthesized expression is a `(`, then an expression, called the enclosed operand, and then a `)`.

[expr.paren.evaluation]

Parenthesized expressions evaluate to the value of the enclosed operand.

[expr.paren.place-or-value]

Unlike other expressions, parenthesized expressions are both place expressions and value expressions. When the enclosed operand is a place expression, it is a place expression and when the enclosed operand is a value expression, it is a value expression.

[expr.paren.override-precedence]

Parentheses can be used to explicitly modify the precedence order of subexpressions within an expression.

An example of a parenthesized expression:

    #![allow(unused)]
    fn main() {
    let x: i32 = 2 + 3 * 4; // not parenthesized
    let y: i32 = (2 + 3) * 4; // parenthesized
    assert_eq!(x, 14);
    assert_eq!(y, 20);
    }

An example of a necessary use of parentheses is when calling a function pointer that is a member of a struct:

    #![allow(unused)]
    fn main() {
    struct A {
       f: fn() -> &'static str
    }
    impl A {
       fn f(&self) -> &'static str {
           "The method f"
       }
    }
    let a = A{f: || "The field f"};

    assert_eq!( a.f (), "The method f");
    assert_eq!((a.f)(), "The field f");
    }

[expr.array]

# Array and array index expressions

## Array expressions

[expr.array.syntax]

Syntax
ArrayExpression → [ ArrayElements? ]

ArrayElements →
Expression ( , Expression )* ,?
| Expression ; Expression

[expr.array.constructor]

Array expressions construct arrays. Array expressions come in two forms.

[expr.array.array]

The first form lists out every value in the array.

[expr.array.array-syntax]

The syntax for this form is a comma-separated list of expressions of uniform type enclosed in square brackets.

[expr.array.array-behavior]

This produces an array containing each of these values in the order they are written.

[expr.array.repeat]

The syntax for the second form is two expressions separated by a semicolon (`;`) enclosed in square brackets.

[expr.array.repeat-operand]

The expression before the `;` is called the repeat operand.

[expr.array.length-operand]

The expression after the `;` is called the length operand.

[expr.array.length-restriction]

The length operand must either be an inferred const or be a constant expression of type `usize` (e.g. a literal or a constant item).

    #![allow(unused)]
    fn main() {
    const C: usize = 1;
    let _: [u8; C] = [0; 1]; // Literal.
    let _: [u8; C] = [0; C]; // Constant item.
    let _: [u8; C] = [0; _]; // Inferred const.
    let _: [u8; C] = [0; (((_)))]; // Inferred const.
    }

> Note

> In an array expression, an inferred const is parsed as an expression but then semantically treated as a separate kind of const generic argument.

[expr.array.repeat-behavior]

An array expression of this form creates an array with the length of the value of the length operand with each element being a copy of the repeat operand. That is, `[a; b]` creates an array containing `b` copies of the value of `a`.

[expr.array.repeat-copy]

If the length operand has a value greater than 1 then this requires the repeat operand to have a type that implements `Copy`, to be a const block expression, or to be a path to a constant item.

[expr.array.repeat-const-item]

When the repeat operand is a const block or a path to a constant item, it is evaluated the number of times specified in the length operand.

[expr.array.repeat-evaluation-zero]

If that value is `0`, then the const block or constant item is not evaluated at all.

[expr.array.repeat-non-const]

For expressions that are neither a const block nor a path to a constant item, it is evaluated exactly once, and then the result is copied the length operand’s value times.

    #![allow(unused)]
    fn main() {
    [1, 2, 3, 4];
    ["a", "b", "c", "d"];
    [0; 128];              // array with 128 zeros
    [0u8, 0u8, 0u8, 0u8,];
    [[1, 0, 0], [0, 1, 0], [0, 0, 1]]; // 2D array
    const EMPTY: Vec<i32> = Vec::new();
    [EMPTY; 2];
    }

[expr.array.index]

## Array and slice indexing expressions

[expr.array.index.syntax]

Syntax
IndexExpression → Expression [ Expression ]

[expr.array.index.array]

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.

[expr.array.index.trait]

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. Just as with methods, Rust will also insert dereference operations on `a` repeatedly to find an implementation.

[expr.array.index.zero-index]

Indices are zero-based for arrays and slices.

[expr.array.index.const]

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.

    #![allow(unused)]
    fn main() {
    // 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]];
    b[1][2];                  // 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
    }

[expr.array.index.trait-impl]

The array index expression can be implemented for types other than arrays and slices by implementing the Index and IndexMut traits.

[expr.tuple]

# Tuple and tuple indexing expressions

## Tuple expressions

[expr.tuple.syntax]

Syntax
TupleExpression → ( TupleElements? )

TupleElements → ( Expression , )+ Expression?

[expr.tuple.result]

A tuple expression constructs tuple values.

[expr.tuple.intro]

The syntax for tuple expressions is a parenthesized, comma separated list of expressions, called the tuple initializer operands.

[expr.tuple.unary-tuple-restriction]

1-ary tuple expressions require a comma after their tuple initializer operand to be disambiguated with a parenthetical expression.

[expr.tuple.value]

Tuple expressions are a value expression that evaluate into a newly constructed value of a tuple type.

[expr.tuple.type]

The number of tuple initializer operands is the arity of the constructed tuple.

[expr.tuple.unit]

Tuple expressions without any tuple initializer operands produce the unit tuple.

[expr.tuple.fields]

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)`

[expr.tuple-index]

## Tuple indexing expressions

[expr.tuple-index.syntax]

Syntax
TupleIndexingExpression → Expression . TUPLE_INDEX

[expr.tuple-index.intro]

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.

[expr.tuple-index.index-syntax]

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`.

[expr.tuple-index.required-type]

The type of the tuple operand must be a tuple type or a tuple struct.

[expr.tuple-index.index-name-operand]

The tuple index must be a name of a field of the type of the tuple operand.

[expr.tuple-index.result]

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:

    #![allow(unused)]
    fn main() {
    // Indexing a tuple
    let pair = ("a string", 2);
    assert_eq!(pair.1, 2);

    // Indexing a tuple struct
    struct Point(f32, f32);
    let point = Point(1.0, 0.0);
    assert_eq!(point.0, 1.0);
    assert_eq!(point.1, 0.0);
    }

> Note

> 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.

> Note

> Although arrays and slices also have elements, you must use an array or slice indexing expression or a slice pattern to access their elements.

[expr.struct]

# Struct expressions

[expr.struct.syntax]

Syntax
StructExpression →
PathInExpression { ( StructExprFields | StructBase )? }

StructExprFields →
StructExprField ( , StructExprField )* ( , StructBase | ,? )

StructExprField →
OuterAttribute*
(
IDENTIFIER
| ( IDENTIFIER | TUPLE_INDEX ) : Expression
)

StructBase → .. Expression

[expr.struct.intro]

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:

    #![allow(unused)]
    fn main() {
    struct Point { x: f64, y: f64 }
    struct NothingInMe { }
    mod game { pub struct User<'a> { pub name: &'a str, pub age: u32, pub score: usize } }
    enum Enum { Variant {} }
    Point {x: 10.0, y: 20.0};
    NothingInMe {};
    let u = game::User {name: "Joe", age: 35, score: 100_000};
    Enum::Variant {};
    }

> Note

> 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.

>     #![allow(unused)]
>     fn main() {
>     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:

>     #![allow(unused)]
>     fn main() {
>     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.

>     #![allow(unused)]
>     fn main() {
>     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 {};
>     }

[expr.struct.field]

## Field struct expression

[expr.struct.field.intro]

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.

[expr.struct.field.union-constraint]

A value of a union type can only be created using this syntax, and it must specify exactly one field.

[expr.struct.update]

## Functional update syntax

[expr.struct.update.intro]

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.

[expr.struct.update.base-same-type]

The expression following `..` (the base) must have the same struct type as the new struct type being formed.

[expr.struct.update.fields]

The entire expression uses the given values for the fields that were specified and moves or copies the remaining fields from the base expression.

[expr.struct.update.visibility-constraint]

As with all struct expressions, all of the fields of the struct must be visible, even those not explicitly named.

    #![allow(unused)]
    fn main() {
    struct Point3d { x: i32, y: i32, z: i32 }
    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);
    }

[expr.struct.brace-restricted-positions]

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.

[expr.struct.tuple-field]

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:

    #![allow(unused)]
    fn main() {
    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.
    }

[expr.struct.field.named]

### 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:

    #![allow(unused)]
    fn main() {
    struct Point3d { x: i32, y: i32, z: i32 }
    let x = 0;
    let y_value = 0;
    let z = 0;
    Point3d { x: x, y: y_value, z: z };
    Point3d { x, y: y_value, z };
    }

[expr.call]

# Call expressions

[expr.call.syntax]

Syntax
CallExpression → Expression ( CallParams? )

CallParams → Expression ( , Expression )* ,?

[expr.call.intro]

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.

[expr.call.convergence]

If the function eventually returns, then the expression completes.

[expr.call.trait]

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.

[expr.call.autoref-deref]

An automatic borrow will be taken if needed. The function operand will also be automatically dereferenced as required.

Some examples of call expressions:

    #![allow(unused)]
    fn main() {
    fn add(x: i32, y: i32) -> i32 { 0 }
    let three: i32 = add(1i32, 2i32);
    let name: &'static str = (|| "Rust")();
    }

[expr.call.desugar]

## Disambiguating function calls

[expr.call.desugar.fully-qualified]

All function calls are sugar for a more explicit fully-qualified syntax.

[expr.call.desugar.ambiguity]

Function calls may need to be fully qualified, depending on the ambiguity of a call in light of in-scope items.

> Note

> 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.

[expr.call.desugar.limits]

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()`

[expr.call.desugar.explicit-path]

To resolve the ambiguity, the programmer may refer to their desired method or function using more specific paths, types, or traits.

For example,

    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.

[expr.method]

# Method-call expressions

[expr.method.syntax]

Syntax
MethodCallExpression → Expression . PathExprSegment ( CallParams? )

[expr.method.intro]

A method call consists of an expression (the receiver) followed by a single dot, an expression path segment, and a parenthesized expression-list.

[expr.method.target]

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.

    #![allow(unused)]
    fn main() {
    let pi: Result<f32, _> = "3.14".parse();
    let log_pi = pi.unwrap_or(1.0).log(2.72);
    assert!(1.14 < log_pi && log_pi < 1.15)
    }

[expr.method.autoref-deref]

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:

[expr.method.candidate-receivers]

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 unsized coercion at the end, and adding the result type if that is successful.

[expr.method.candidate-receivers-refs]

Then, for each candidate `T`, add `&T` and `&mut T` to the list immediately after `T`.

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]`.

[expr.method.candidate-search]

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`).
2. 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.

> Note

> 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.

>     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();
>     }

[expr.method.ambiguous-target]

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.

[expr.method.receiver-constraints]

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.

[expr.method.ambiguous-search]

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.

[expr.method.edition2021]

> 2021 Edition differences

> 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.

> Warning

> 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.

[expr.field]

# Field access expressions

[expr.field.syntax]

Syntax
FieldExpression → Expression . IDENTIFIER

[expr.field.intro]

A field expression is a place expression that evaluates to the location of a field of a struct or union.

[expr.field.mut]

When the operand is mutable, the field expression is also mutable.

[expr.field.form]

The syntax for a field expression is an expression, called the container operand, then a `.`, and finally an identifier.

[expr.field.not-method-call]

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.

> Note

> Wrap the field expression in a parenthesized expression to use it in a call expression.

>     #![allow(unused)]
>     fn main() {
>     struct HoldsCallable<F: Fn()> { callable: F }
>     let holds_callable = HoldsCallable { callable: || () };

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

>     // Valid
>     (holds_callable.callable)();
>     }

Examples:

    mystruct.myfield;
    foo().x;
    (Struct {a: 10, b: 20}).a;
    (mystruct.function_field)() // Call expression containing a field expression

[expr.field.autoref-deref]

## 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.

[expr.field.borrow]

## 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`.

    #![allow(unused)]
    fn main() {
    struct A { f1: String, f2: String, f3: String }
    let mut x: A;
    x = A {
        f1: "f1".to_string(),
        f2: "f2".to_string(),
        f3: "f3".to_string()
    };
    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
    }

[expr.closure]

# Closure expressions

[expr.closure.syntax]

Syntax
ClosureExpression →
async?​1
move?
( || | | ClosureParameters? | )
( Expression | -> TypeNoBounds BlockExpression )

ClosureParameters → ClosureParam ( , ClosureParam )* ,?

ClosureParam → OuterAttribute* PatternNoTopAlt ( : Type )?

[expr.closure.intro]

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.

[expr.closure.param-type]

The optional type after each pattern is a type annotation for the pattern.

[expr.closure.explicit-type-body]

If there is a return type, the closure body must be a block.

[expr.closure.parameter-restriction]

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.

[expr.closure.unique-type]

Each closure expression has a unique, anonymous type.

[expr.closure.captures]

Significantly, closure expressions capture their environment, which regular function definitions do not.

[expr.closure.capture-inference]

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.

[expr.closure.capture-mut-ref]

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.

[expr.closure.capture-move]

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`.

[expr.closure.trait-impl]

## Closure trait implementations

Which traits the closure type implement 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.

[expr.closure.async]

## Async closures

[expr.closure.async.intro]

Closures marked with the `async` keyword indicate that they are asynchronous in an analogous way to an async function.

[expr.closure.async.future]

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.

    #![allow(unused)]
    fn main() {
    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;
    }
    }

[expr.closure.async.edition2018]

> 2018 Edition differences

> Async closures are only available beginning with Rust 2018.

## 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.

    #![allow(unused)]
    fn main() {
    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));
    }

## Attributes on closure parameters

[expr.closure.param-attributes]

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

1. The `async` qualifier is not allowed in the 2015 edition. ↩

[expr.loop]

# Loops and other breakable expressions

[expr.loop.syntax]

Syntax
LoopExpression →
LoopLabel? (
InfiniteLoopExpression
| PredicateLoopExpression
| IteratorLoopExpression
| LabelBlockExpression
)

[expr.loop.intro]

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`.

[expr.loop.break-label]

All four types of loop support `break` expressions, and labels.

[expr.loop.continue-label]

All except labeled block expressions support `continue` expressions.

[expr.loop.explicit-result]

Only `loop` and labeled block expressions support evaluation to non-trivial values.

[expr.loop.infinite]

## Infinite loops

[expr.loop.infinite.syntax]

Syntax
InfiniteLoopExpression → loop BlockExpression

[expr.loop.infinite.intro]

A `loop` expression repeats execution of its body continuously: `loop { println!("I live."); }`.

[expr.loop.infinite.diverging]

A `loop` expression without an associated `break` expression is diverging and has type `!`.

[expr.loop.infinite.break]

A `loop` expression containing associated `break` expression(s) may terminate, and must have type compatible with the value of the `break` expression(s).

[expr.loop.while]

## Predicate loops

[expr.loop.while.grammar]

Syntax
PredicateLoopExpression → while Conditions BlockExpression

[expr.loop.while.intro]

A `while` loop expression allows repeating the evaluation of a block while a set of conditions remain true.

[expr.loop.while.syntax]

The syntax of a `while` expression is a sequence of one or more condition operands separated by `&&`, followed by a BlockExpression.

[expr.loop.while.condition]

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 scrutinees, then the loop body block executes.

[expr.loop.while.repeat]

After the loop body successfully executes, the condition operands are re-evaluated to determine if the body should be executed again.

[expr.loop.while.exit]

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.

[expr.loop.while.eval]

A `while` expression evaluates to `()`.

An example:

    #![allow(unused)]
    fn main() {
    let mut i = 0;

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

[expr.loop.while.let]

### `while let` patterns

[expr.loop.while.let.intro]

`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:

    #![allow(unused)]
    fn main() {
    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;
    }
    }

[expr.loop.while.let.desugar]

A `while let` loop is equivalent to a `loop` expression containing a `match` expression as follows.

    'label: while let PATS = EXPR {
        /* loop body */
    }

is equivalent to

    'label: loop {
        match EXPR {
            PATS => { /* loop body */ },
            _ => break,
        }
    }

[expr.loop.while.let.or-pattern]

Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:

    #![allow(unused)]
    fn main() {
    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);
    }
    }

[expr.loop.while.chains]

### `while` condition chains

[expr.loop.while.chains.intro]

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:

    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;
        }
    }

[expr.loop.for]

## Iterator loops

[expr.loop.for.syntax]

Syntax
IteratorLoopExpression →
for Pattern in Expressionexcept StructExpression BlockExpression

[expr.loop.for.intro]

A `for` expression is a syntactic construct for looping over elements provided by an implementation of `std::iter::IntoIterator`.

[expr.loop.for.condition]

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:

    #![allow(unused)]
    fn main() {
    let v = &["apples", "cake", "coffee"];

    for text in v {
        println!("I like {}.", text);
    }
    }

An example of a for loop over a series of integers:

    #![allow(unused)]
    fn main() {
    let mut sum = 0;
    for n in 1..11 {
        sum += n;
    }
    assert_eq!(sum, 55);
    }

[expr.loop.for.desugar]

A `for` loop is equivalent to a `loop` expression containing a `match` expression as follows:

    'label: for PATTERN in iter_expr {
        /* loop body */
    }

is equivalent to

    {
        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
    }

[expr.loop.for.lang-items]

`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.

> Note

> 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.

[expr.loop.label]

## Loop labels

[expr.loop.label.syntax]

Syntax
LoopLabel → LIFETIME_OR_LABEL :

[expr.loop.label.intro]

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 {}`.

[expr.loop.label.control-flow]

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.

[expr.loop.label.ref]

Labels follow the hygiene and shadowing rules of local variables. For example, this code will print “outer loop”:

    #![allow(unused)]
    fn main() {
    'a: loop {
        'a: loop {
            break 'a;
        }
        print!("outer loop");
        break 'a;
    }
    }

`'_` is not a valid loop label.

[expr.loop.break]

## `break` expressions

[expr.loop.break.syntax]

Syntax
BreakExpression → break LIFETIME_OR_LABEL? Expression?

[expr.loop.break.intro]

When `break` is encountered, execution of the associated loop body is immediately terminated, for example:

    #![allow(unused)]
    fn main() {
    let mut last = 0;
    for x in 1..100 {
        if x > 12 {
            break;
        }
        last = x;
    }
    assert_eq!(last, 12);
    }

[expr.loop.break.label]

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:

    #![allow(unused)]
    fn main() {
    'outer: loop {
        while true {
            break 'outer;
        }
    }
    }

[expr.loop.break.value]

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`.

[expr.loop.block-labels]

## Labeled block expressions

[expr.loop.block-labels.syntax]

Syntax
LabelBlockExpression → BlockExpression

[expr.loop.block-labels.intro]

Labeled block expressions are exactly like block expressions, except that they allow using `break` expressions within the block.

[expr.loop.block-labels.break]

Unlike loops, `break` expressions within a labeled block expression must have a label (i.e. the label is not optional).

[expr.loop.block-labels.label-required]

Similarly, labeled block expressions must begin with a label.

    #![allow(unused)]
    fn main() {
    fn do_thing() {}
    fn condition_not_met() -> bool { true }
    fn do_next_thing() {}
    fn do_last_thing() {}
    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
    };
    }

[expr.loop.continue]

## `continue` expressions

[expr.loop.continue.syntax]

Syntax
ContinueExpression → continue LIFETIME_OR_LABEL?

[expr.loop.continue.intro]

When `continue` is encountered, the current iteration of the associated loop body is immediately terminated, returning control to the loop head.

[expr.loop.continue.while]

In the case of a `while` loop, the head is the conditional operands controlling the loop.

[expr.loop.continue.for]

In the case of a `for` loop, the head is the call-expression controlling the loop.

[expr.loop.continue.label]

Like `break`, `continue` is normally associated with the innermost enclosing loop, but `continue 'label` may be used to specify the loop affected.

[expr.loop.continue.in-loop-only]

A `continue` expression is only permitted in the body of a loop.

[expr.loop.break-value]

## `break` and loop values

[expr.loop.break-value.intro]

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:

    #![allow(unused)]
    fn main() {
    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);
    }

[expr.loop.break-value.loop]

In the case a `loop` has an associated `break`, it is not considered diverging, and the `loop` must have a type compatible with each `break` expression. `break` without an expression is considered identical to `break` with expression `()`.

[expr.range]

# Range expressions

[expr.range.syntax]

Syntax
RangeExpression →
RangeExpr
| RangeFromExpr
| RangeToExpr
| RangeFullExpr
| RangeInclusiveExpr
| RangeToInclusiveExpr

RangeExpr → Expression .. Expression

RangeFromExpr → Expression ..

RangeToExpr → .. Expression

RangeFullExpr → ..

RangeInclusiveExpr → Expression ..= Expression

RangeToInclusiveExpr → ..= Expression

[expr.range.behavior]

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:

    #![allow(unused)]
    fn main() {
    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
    }

[expr.range.equivalence]

The following expressions are equivalent.

    #![allow(unused)]
    fn main() {
    let x = std::ops::Range {start: 0, end: 10};
    let y = 0..10;

    assert_eq!(x, y);
    }

[expr.range.for]

Ranges can be used in `for` loops:

    #![allow(unused)]
    fn main() {
    for i in 1..11 {
        println!("{}", i);
    }
    }

[expr.if]

# `if` expressions

[expr.if.syntax]

Syntax
IfExpression →
if Conditions BlockExpression
( else ( BlockExpression | IfExpression ) )?

Conditions →
Expressionexcept StructExpression
| LetChain

LetChain → LetChainCondition ( && LetChainCondition )*

LetChainCondition →
Expressionexcept ExcludedConditions
| OuterAttribute* let Pattern = Scrutineeexcept ExcludedConditions

ExcludedConditions →
StructExpression
| LazyBooleanExpression
| RangeExpr
| RangeFromExpr
| RangeInclusiveExpr
| AssignmentExpression
| CompoundAssignmentExpression

[expr.if.intro]

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.

[expr.if.condition]

Condition operands must be either an Expression with a boolean type or a conditional `let` match.

[expr.if.condition-true]

If all of the condition operands evaluate to `true` and all of the `let` patterns successfully match their scrutinees, the consequent block is executed and any subsequent `else if` or `else` block is skipped.

[expr.if.else-if]

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.

[expr.if.else]

If all `if` and `else if` conditions evaluate to `false` then any `else` block is executed.

[expr.if.result]

An `if` expression evaluates to the same value as the executed block, or `()` if no block is evaluated.

[expr.if.type]

An `if` expression must have the same type in all situations.

    #![allow(unused)]
    fn main() {
    let x = 3;
    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");
    }

[expr.if.let]

## `if let` patterns

[expr.if.let.intro]

`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:

    #![allow(unused)]
    fn main() {
    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");
    }
    }

[expr.if.let.or-pattern]

Multiple patterns may be specified with the `|` operator. This has the same semantics as with `|` in `match` expressions:

    #![allow(unused)]
    fn main() {
    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);
    }
    }

[expr.if.chains]

## Chains of conditions

[expr.if.chains.intro]

Multiple condition operands can be separated with `&&`.

[expr.if.chains.order]

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.

[expr.if.chains.bindings]

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:

    #![allow(unused)]
    fn main() {
    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:

    #![allow(unused)]
    fn main() {
    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");
                }
            }
        }
    }
    }

[expr.if.chains.or]

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:

    #![allow(unused)]
    fn main() {
    let foo = Some(123);
    let condition1 = true;
    let condition2 = false;
    // Parentheses are required here.
    if let Some(x) = foo && (condition1 || condition2) { /*...*/ }
    }

[expr.if.edition2024]

> 2024 Edition differences

> Before the 2024 edition, let chains are not supported. That is, the LetChain grammar is not allowed in an `if` expression.

[expr.match]

# `match` expressions

[expr.match.syntax]

Syntax
MatchExpression →
match Scrutinee {
InnerAttribute*
MatchArms?
}

Scrutinee → Expressionexcept StructExpression

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

MatchArm → OuterAttribute* Pattern MatchArmGuard?

MatchArmGuard → if Expression

[expr.match.intro]

A `match` expression branches on a pattern. The exact form of matching that occurs depends on the pattern.

[expr.match.scrutinee]

A `match` expression has a scrutinee expression, which is the value to compare to the patterns.

[expr.match.scrutinee-constraint]

The scrutinee expression and the patterns must have the same type.

[expr.match.scrutinee-behavior]

A `match` behaves differently depending on whether or not the scrutinee expression is a place expression or value expression.

[expr.match.scrutinee-value]

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.

[expr.match.scrutinee-place]

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:

    #![allow(unused)]
    fn main() {
    let x = 1;

    match x {
        1 => println!("one"),
        2 => println!("two"),
        3 => println!("three"),
        4 => println!("four"),
        5 => println!("five"),
        _ => println!("something else"),
    }
    }

[expr.match.pattern-vars]

Variables bound within the pattern are scoped to the match guard and the arm’s expression.

[expr.match.pattern-var-binding]

The binding mode (move, copy, or reference) depends on the pattern.

[expr.match.or-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.

    #![allow(unused)]
    fn main() {
    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!(),
    }
    }

> Note

> 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.

[expr.match.or-patterns-restriction]

Every binding in each `|` separated pattern must appear in all of the patterns in the arm.

[expr.match.binding-restriction]

Every binding of the same name must have the same type, and have the same binding mode.

[expr.match.guard]

## Match guards

[expr.match.guard.intro]

Match arms can accept match guards to further refine the criteria for matching a case.

[expr.match.guard.type]

Pattern guards appear after the pattern and consist of a `bool`-typed expression following the `if` keyword.

[expr.match.guard.behavior]

When the pattern matches successfully, the pattern guard expression is executed. If the expression evaluates to true, the pattern is successfully matched against.

[expr.match.guard.next]

Otherwise, the next pattern, including other matches with the `|` operator in the same arm, is tested.

    #![allow(unused)]
    fn main() {
    let maybe_digit = Some(0);
    fn process_digit(i: i32) { }
    fn process_other(i: i32) { }
    let message = match maybe_digit {
        Some(x) if x < 10 => process_digit(x),
        Some(x) => process_other(x),
        None => panic!(),
    };
    }

> Note

> Multiple matches using the `|` operator can cause the pattern guard and the side effects it has to execute multiple times. For example:

>     #![allow(unused)]
>     fn main() {
>     use std::cell::Cell;
>     let i : Cell<i32> = Cell::new(0);
>     match 1 {
>         1 | _ if { i.set(i.get() + 1); false } => {}
>         _ => {}
>     }
>     assert_eq!(i.get(), 2);
>     }

[expr.match.guard.bound-variables]

A pattern guard may refer to the variables bound within the pattern they follow.

[expr.match.guard.shared-ref]

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.

[expr.match.guard.value]

Only when the guard evaluates to true 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.

[expr.match.guard.no-mutation]

Moreover, by holding a shared reference while evaluating the guard, mutation inside guards is also prevented.

[expr.match.attributes]

## Attributes on match arms

[expr.match.attributes.outer]

Outer attributes are allowed on match arms. The only attributes that have meaning on match arms are `cfg` and the lint check attributes.

[expr.match.attributes.inner]

Inner attributes are allowed directly after the opening brace of the match expression in the same expression contexts as attributes on block expressions.

[expr.return]

# `return` expressions

[expr.return.syntax]

Syntax
ReturnExpression → return Expression?

[expr.return.intro]

Return expressions are denoted with the keyword `return`.

[expr.return.behavior]

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.

An example of a `return` expression:

    #![allow(unused)]
    fn main() {
    fn max(a: i32, b: i32) -> i32 {
        if a > b {
            return a;
        }
        return b;
    }
    }

[expr.await]

# Await expressions

[expr.await.syntax]

Syntax
AwaitExpression → Expression . await

[expr.await.intro]

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.

[expr.await.construct]

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.

[expr.await.allowed-positions]

Await expressions are legal only within an async context, like an `async fn`, `async` closure, or `async` block.

[expr.await.effects]

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.

[expr.await.edition2018]

> 2018 Edition differences

> Await expressions are only available beginning with Rust 2018.

[expr.await.task]

## 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.

[expr.await.desugar]

## Approximate desugaring

Effectively, an await expression is roughly equivalent to the following non-normative desugaring:

    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.

[expr.placeholder]

# `_` expressions

[expr.placeholder.syntax]

Syntax
UnderscoreExpression → _

[expr.placeholder.intro]

Underscore expressions, denoted with the symbol `_`, are used to signify a placeholder in a destructuring assignment.

[expr.placeholder.lhs-assignment-only]

They may only appear in the left-hand side of an assignment.

[expr.placeholder.pattern]

Note that this is distinct from the wildcard pattern.

Examples of `_` expressions:

    #![allow(unused)]
    fn main() {
    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;
    }

[patterns]

# Patterns

[patterns.syntax]

Syntax
Pattern → |? PatternNoTopAlt ( | PatternNoTopAlt )*

PatternNoTopAlt →
PatternWithoutRange
| RangePattern

PatternWithoutRange →
LiteralPattern
| IdentifierPattern
| WildcardPattern
| RestPattern
| ReferencePattern
| StructPattern
| TupleStructPattern
| TuplePattern
| GroupedPattern
| SlicePattern
| PathPattern
| MacroInvocation

[patterns.intro]

Patterns are used to match values against structures and to, optionally, bind variables to values inside these structures. They are also used in variable declarations and parameters for functions and closures.

The pattern in the following example does four things:

- Tests if `person` has the `car` field filled with something.
- Tests if the person’s `age` field is between 13 and 19, and binds its value to the `person_age` variable.
- Binds a reference to the `name` field to the variable `person_name`.
- Ignores the rest of the fields of `person`. The remaining fields can have any value and are not bound to any variables.

    #![allow(unused)]
    fn main() {
    struct Car;
    struct Computer;
    struct Person {
        name: String,
        car: Option<Car>,
        computer: Option<Computer>,
        age: u8,
    }
    let person = Person {
        name: String::from("John"),
        car: Some(Car),
        computer: None,
        age: 15,
    };
    if let
        Person {
            car: Some(_),
            age: person_age @ 13..=19,
            name: ref person_name,
            ..
        } = person
    {
        println!("{} has a car and is {} years old.", person_name, person_age);
    }
    }

[patterns.usage]

Patterns are used in:

[patterns.let]

- `let` declarations

[patterns.param]

- Function and closure parameters

[patterns.match]

- `match` expressions

[patterns.if-let]

- `if let` expressions

[patterns.while-let]

- `while let` expressions

[patterns.for]

- `for` expressions

[patterns.destructure]

## Destructuring

[patterns.destructure.intro]

Patterns can be used to destructure structs, enums, and tuples. Destructuring breaks up a value into its component pieces. The syntax used is almost the same as when creating such values.

[patterns.destructure.wildcard]

In a pattern whose scrutinee expression has a `struct`, `enum` or `tuple` type, a wildcard pattern (`_`) stands in for a single data field, whereas an et cetera or rest pattern (`..`) stands in for all the remaining fields of a particular variant.

[patterns.destructure.named-field-shorthand]

When destructuring a data structure with named (but not numbered) fields, it is allowed to write `fieldname` as a shorthand for `fieldname: fieldname`.

    #![allow(unused)]
    fn main() {
    enum Message {
        Quit,
        WriteString(String),
        Move { x: i32, y: i32 },
        ChangeColor(u8, u8, u8),
    }
    let message = Message::Quit;
    match message {
        Message::Quit => println!("Quit"),
        Message::WriteString(write) => println!("{}", &write),
        Message::Move{ x, y: 0 } => println!("move {} horizontally", x),
        Message::Move{ .. } => println!("other move"),
        Message::ChangeColor { 0: red, 1: green, 2: _ } => {
            println!("color change, red: {}, green: {}", red, green);
        }
    };
    }

[patterns.refutable]

## Refutability

A pattern is said to be refutable when it has the possibility of not being matched by the value it is being matched against. Irrefutable patterns, on the other hand, always match the value they are being matched against. Examples:

    #![allow(unused)]
    fn main() {
    let (x, y) = (1, 2);               // "(x, y)" is an irrefutable pattern

    if let (a, 3) = (1, 2) {           // "(a, 3)" is refutable, and will not match
        panic!("Shouldn't reach here");
    } else if let (a, 4) = (3, 4) {    // "(a, 4)" is refutable, and will match
        println!("Matched ({}, 4)", a);
    }
    }

[patterns.literal]

## Literal patterns

[patterns.literal.syntax]

Syntax
LiteralPattern → -? LiteralExpression

[patterns.literal.intro]

Literal patterns match exactly the same value as what is created by the literal. Since negative numbers are not literals, literals in patterns may be prefixed by an optional minus sign, which acts like the negation operator.

> Warning

> C string and raw C string literals are accepted in literal patterns, but `&CStr` doesn’t implement structural equality (`#[derive(Eq, PartialEq)]`) and therefore any such `match` on a `&CStr` will be rejected with a type error.

[patterns.literal.refutable]

Literal patterns are always refutable.

Examples:

    #![allow(unused)]
    fn main() {
    for i in -2..5 {
        match i {
            -1 => println!("It's minus one"),
            1 => println!("It's a one"),
            2|4 => println!("It's either a two or a four"),
            _ => println!("Matched none of the arms"),
        }
    }
    }

[patterns.ident]

## Identifier patterns

[patterns.ident.syntax]

Syntax
IdentifierPattern → ref? mut? IDENTIFIER ( @ PatternNoTopAlt )?

[patterns.ident.intro]

Identifier patterns bind the value they match to a variable in the value namespace.

[patterns.ident.unique]

The identifier must be unique within the pattern.

[patterns.ident.scope]

The variable will shadow any variables of the same name in scope. The scope of the new binding depends on the context of where the pattern is used (such as a `let` binding or a `match` arm).

[patterns.ident.bare]

Patterns that consist of only an identifier, possibly with a `mut`, match any value and bind it to that identifier. This is the most commonly used pattern in variable declarations and parameters for functions and closures.

    #![allow(unused)]
    fn main() {
    let mut variable = 10;
    fn sum(x: i32, y: i32) -> i32 {
       x + y
    }
    }

[patterns.ident.scrutinized]

To bind the matched value of a pattern to a variable, use the syntax `variable @ subpattern`. For example, the following binds the value 2 to `e` (not the entire range: the range here is a range subpattern).

    #![allow(unused)]
    fn main() {
    let x = 2;

    match x {
        e @ 1 ..= 5 => println!("got a range element {}", e),
        _ => println!("anything"),
    }
    }

[patterns.ident.move]

By default, identifier patterns bind a variable to a copy of or move from the matched value depending on whether the matched value implements `Copy`.

[patterns.ident.ref]

This can be changed to bind to a reference by using the `ref` keyword, or to a mutable reference using `ref mut`. For example:

    #![allow(unused)]
    fn main() {
    let a = Some(10);
    match a {
        None => (),
        Some(value) => (),
    }

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

In the first match expression, the value is copied (or moved). In the second match, a reference to the same memory location is bound to the variable value. This syntax is needed because in destructuring subpatterns the `&` operator can’t be applied to the value’s fields. For example, the following is not valid:

    #![allow(unused)]
    fn main() {
    struct Person {
       name: String,
       age: u8,
    }
    let value = Person { name: String::from("John"), age: 23 };
    if let Person { name: &person_name, age: 18..=150 } = value { }
    }

To make it valid, write the following:

    #![allow(unused)]
    fn main() {
    struct Person {
       name: String,
       age: u8,
    }
    let value = Person { name: String::from("John"), age: 23 };
    if let Person { name: ref person_name, age: 18..=150 } = value { }
    }

[patterns.ident.ref-ignored]

Thus, `ref` is not something that is being matched against. Its objective is exclusively to make the matched binding a reference, instead of potentially copying or moving what was matched.

[patterns.ident.precedent]

Path patterns take precedence over identifier patterns.

> Note

> When a pattern is a single-segment identifier, the grammar is ambiguous whether it means an IdentifierPattern or a PathPattern. This ambiguity can only be resolved after name resolution.

>     #![allow(unused)]
>     fn main() {
>     const EXPECTED_VALUE: u8 = 42;
>     //    ^^^^^^^^^^^^^^ That this constant is in scope affects how the
>     //                   patterns below are treated.

>     fn check_value(x: u8) -> Result<u8, u8> {
>         match x {
>             EXPECTED_VALUE => Ok(x),
>         //  ^^^^^^^^^^^^^^ Parsed as a `PathPattern` that resolves to
>         //                 the 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));
>     }

[patterns.ident.constraint]

It is an error if `ref` or `ref mut` is specified and the identifier shadows a constant.

[patterns.ident.refutable]

Identifier patterns are irrefutable if the `@` subpattern is irrefutable or the subpattern is not specified.

[patterns.ident.binding]

### Binding modes

[patterns.ident.binding.intro]

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:

    #![allow(unused)]
    fn main() {
    let x: &Option<i32> = &Some(3);
    if let Some(y) = x {
        // y was converted to `ref y` and its type is &i32
    }
    }

[patterns.ident.binding.non-reference]

Non-reference patterns include all patterns except bindings, wildcard patterns (`_`), `const` patterns of reference types, and reference patterns.

[patterns.ident.binding.default-mode]

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.

[patterns.ident.binding.move]

The default binding mode starts in “move” mode which uses move semantics.

[patterns.ident.binding.top-down]

When matching a pattern, the compiler starts from the outside of the pattern and works inwards.

[patterns.ident.binding.auto-deref]

Each time a reference is matched using a non-reference pattern, it will automatically dereference the value and update the default binding mode.

[patterns.ident.binding.ref]

References will set the default binding mode to `ref`.

[patterns.ident.binding.ref-mut]

Mutable references will set the mode to `ref mut` unless the mode is already `ref` in which case it remains `ref`.

[patterns.ident.binding.nested-references]

If the automatically dereferenced value is still a reference, it is dereferenced and this process repeats.

[patterns.ident.binding.mode-limitations-binding]

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:

    #![allow(unused)]
    fn main() {
    let [mut x] = &[()]; //~ ERROR
    let [ref x] = &[()]; //~ ERROR
    let [ref mut x] = &mut [()]; //~ ERROR
    }

[patterns.ident.binding.mode-limitations.edition2024]

> 2024 Edition differences

> 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.

[patterns.ident.binding.mode-limitations-reference]

Similarly, a reference pattern may only appear when the default binding mode is “move”. For example, this is not accepted:

    #![allow(unused)]
    fn main() {
    let [&x] = &[&()]; //~ ERROR
    }

[patterns.ident.binding.mode-limitations-reference.edition2024]

> 2024 Edition differences

> 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”.

[patterns.ident.binding.mixed]

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:

    #![allow(unused)]
    fn main() {
    struct Person {
       name: String,
       age: u8,
    }
    let person = Person{ name: String::from("John"), age: 23 };
    // `name` is moved from person and `age` referenced
    let Person { name, ref age } = person;
    }

[patterns.wildcard]

## Wildcard pattern

[patterns.wildcard.syntax]

Syntax
WildcardPattern → _

[patterns.wildcard.intro]

The wildcard pattern (an underscore symbol) matches any value. It is used to ignore values when they don’t matter.

[patterns.wildcard.struct-matcher]

Inside other patterns it matches a single data field (as opposed to the `..` which matches the remaining fields).

[patterns.wildcard.no-binding]

Unlike identifier patterns, it does not copy, move or borrow the value it matches.

Examples:

    #![allow(unused)]
    fn main() {
    let x = 20;
    let (a, _) = (10, x);   // the x is always matched by _
    assert_eq!(a, 10);

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

    // ignore a field from a struct
    struct RGBA {
       r: f32,
       g: f32,
       b: f32,
       a: f32,
    }
    let color = RGBA{r: 0.4, g: 0.1, b: 0.9, a: 0.5};
    let RGBA{r: red, g: green, b: blue, a: _} = color;
    assert_eq!(color.r, red);
    assert_eq!(color.g, green);
    assert_eq!(color.b, blue);

    // accept any Some, with any value
    let x = Some(10);
    if let Some(_) = x {}
    }

[patterns.wildcard.refutable]

The wildcard pattern is always irrefutable.

[patterns.rest]

## Rest pattern

[patterns.rest.syntax]

Syntax
RestPattern → ..

[patterns.rest.intro]

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.

[patterns.rest.allowed-patterns]

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.

[patterns.rest.refutable]

The rest pattern is always irrefutable.

Examples:

    #![allow(unused)]
    fn main() {
    let words = vec!["a", "b", "c"];
    let slice = &words[..];
    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);
    }

    let tuple = (1, 2, 3, 4, 5);
    // 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"),
    }
    }

[patterns.range]

## Range patterns

[patterns.range.syntax]

Syntax
RangePattern →
RangeExclusivePattern
| RangeInclusivePattern
| RangeFromPattern
| RangeToExclusivePattern
| RangeToInclusivePattern
| ObsoleteRangePattern​1

RangeExclusivePattern →
RangePatternBound .. RangePatternBound

RangeInclusivePattern →
RangePatternBound ..= RangePatternBound

RangeFromPattern →
RangePatternBound ..

RangeToExclusivePattern →
.. RangePatternBound

RangeToInclusivePattern →
..= RangePatternBound

ObsoleteRangePattern →
RangePatternBound ... RangePatternBound

RangePatternBound →
LiteralPattern
| PathExpression

[patterns.range.intro]

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.

[patterns.range.exclusive]

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'`.

[patterns.range.inclusive]

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'`.

[patterns.range.from]

The from range pattern matches all values greater than or equal to the lower bound. It is written as its lower bound followed by `..`.

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.

[patterns.range.to-exclusive]

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.

[patterns.range.to-inclusive]

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.

[patterns.range.constraint-nonempty]

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`.

[patterns.range.bound]

A bound is written as one of:

- A character, byte, integer, or float literal.
- A `-` followed by an integer or float literal.
- A path.

> Note

> We syntactically accept more than this for a RangePatternBound. We later reject the other things semantically.

[patterns.range.constraint-bound-path]

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.

[patterns.range.type]

The range pattern matches the type of its upper and lower bounds, which must be the same type.

[patterns.range.path-value]

If a bound is a path, the bound matches the type and has the value of the constant the path resolves to.

[patterns.range.literal-value]

If a bound is a literal, the bound matches the type and has the value of the corresponding literal expression.

[patterns.range.negation]

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.

[patterns.range.float-restriction]

For float range patterns, the constant may not be a `NaN`.

Examples:

    #![allow(unused)]
    fn main() {
    let c = 'f';
    let valid_variable = match c {
        'a'..='z' => true,
        'A'..='Z' => true,
        'α'..='ω' => true,
        _ => false,
    };

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

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

    // using paths to constants:
    const TROPOSPHERE_MIN : u8 = 6;
    const TROPOSPHERE_MAX : u8 = 20;

    const STRATOSPHERE_MIN : u8 = TROPOSPHERE_MAX + 1;
    const STRATOSPHERE_MAX : u8 = 50;

    const MESOSPHERE_MIN : u8 = STRATOSPHERE_MAX + 1;
    const MESOSPHERE_MAX : u8 = 85;

    let altitude = 70;

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

    pub mod binary {
        pub const MEGA : u64 = 1024*1024;
        pub const GIGA : u64 = 1024*1024*1024;
    }
    let n_items = 20_832_425;
    let bytes_per_item = 12;
    if let size @ binary::MEGA..=binary::GIGA = n_items * bytes_per_item {
        println!("It fits and occupies {} bytes", size);
    }

    trait MaxValue {
        const MAX: u64;
    }
    impl MaxValue for u8 {
        const MAX: u64 = (1 << 8) - 1;
    }
    impl MaxValue for u16 {
        const MAX: u64 = (1 << 16) - 1;
    }
    impl MaxValue for u32 {
        const MAX: u64 = (1 << 32) - 1;
    }
    // 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",
    });
    }

[patterns.range.refutable]

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.

[patterns.range.refutable-integer]

The range of values for an integer type is the closed range from its minimum to maximum value.

[patterns.range.refutable-char]

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}'`.

[patterns.range.constraint-slice]

RangeFromPattern cannot be used as a top-level pattern for subpatterns in slice patterns. For example, the pattern `[1.., _]` is not a valid pattern.

[patterns.range.edition2021]

> 2021 Edition differences

> 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.

[patterns.ref]

## Reference patterns

[patterns.ref.syntax]

Syntax
ReferencePattern → ( & | && ) mut? PatternWithoutRange

[patterns.ref.intro]

Reference patterns dereference the pointers that are being matched and, thus, borrow them.

For example, these two matches on `x: &i32` are equivalent:

    #![allow(unused)]
    fn main() {
    let int_reference = &3;

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

    assert_eq!(a, b);
    }

[patterns.ref.ref-ref]

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.

[patterns.ref.mut]

Adding the `mut` keyword dereferences a mutable reference. The mutability must match the mutability of the reference.

[patterns.ref.refutable]

Reference patterns are always irrefutable.

[patterns.struct]

## Struct patterns

[patterns.struct.syntax]

Syntax
StructPattern →
PathInExpression {
StructPatternElements?
}

StructPatternElements →
StructPatternFields ( , | , StructPatternEtCetera )?
| StructPatternEtCetera

StructPatternFields →
StructPatternField ( , StructPatternField )*

StructPatternField →
OuterAttribute*
(
TUPLE_INDEX : Pattern
| IDENTIFIER : Pattern
| ref? mut? IDENTIFIER
)

StructPatternEtCetera → ..

[patterns.struct.intro]

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.

[patterns.struct.ignore-rest]

On a struct pattern, the fields are referenced by name, index (in the case of tuple structs) or ignored by use of `..`:

    #![allow(unused)]
    fn main() {
    struct Point {
        x: u32,
        y: u32,
    }
    let s = Point {x: 1, y: 1};

    match s {
        Point {x: 10, y: 20} => (),
        Point {y: 10, x: 20} => (),    // order doesn't matter
        Point {x: 10, ..} => (),
        Point {..} => (),
    }

    struct PointTuple (
        u32,
        u32,
    );
    let t = PointTuple(1, 2);

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

    enum Message {
        Quit,
        Move { x: i32, y: i32 },
    }
    let m = Message::Quit;

    match m {
        Message::Quit => (),
        Message::Move {x: 10, y: 20} => (),
        Message::Move {..} => (),
    }
    }

[patterns.struct.constraint-struct]

If `..` is not used, a struct pattern used to match a struct is required to specify all fields:

    #![allow(unused)]
    fn main() {
    struct Struct {
       a: i32,
       b: char,
       c: bool,
    }
    let mut struct_value = Struct{a: 10, b: 'X', c: false};

    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: _} => (),
    }
    }

[patterns.struct.constraint-union]

A struct pattern used to match a union must specify exactly one field (see Pattern matching on unions).

[patterns.struct.binding-shorthand]

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.

    #![allow(unused)]
    fn main() {
    struct Struct {
       a: i32,
       b: char,
       c: bool,
    }
    let struct_value = Struct{a: 10, b: 'X', c: false};

    let Struct { a, b, c } = struct_value;
    }

[patterns.struct.refutable]

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.

[patterns.struct.namespace]

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.

[patterns.tuple-struct]

## Tuple struct patterns

[patterns.tuple-struct.syntax]

Syntax
TupleStructPattern → PathInExpression ( TupleStructItems? )

TupleStructItems → Pattern ( , Pattern )* ,?

[patterns.tuple-struct.intro]

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.

[patterns.tuple-struct.refutable]

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.

[patterns.tuple-struct.namespace]

A tuple struct pattern matches against the tuple struct or tuple-like enum variant whose constructor is resolved from PathInExpression in the value namespace.

> Note

> 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.

>     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 {} };
>     }
>     // Required due to the odd behavior of `super` within functions.
>     fn main() {}

> 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.

[patterns.tuple]

## Tuple patterns

[patterns.tuple.syntax]

Syntax
TuplePattern → ( TuplePatternItems? )

TuplePatternItems →
Pattern ,
| RestPattern
| Pattern ( , Pattern )+ ,?

[patterns.tuple.intro]

Tuple patterns match tuple values that match all criteria defined by its subpatterns. They are also used to destructure a tuple.

[patterns.tuple.rest-syntax]

The form `(..)` with a single RestPattern is a special form that does not require a comma, and matches a tuple of any size.

[patterns.tuple.refutable]

The tuple pattern is refutable when one of its subpatterns is refutable.

An example of using tuple patterns:

    #![allow(unused)]
    fn main() {
    let pair = (10, "ten");
    let (a, b) = pair;

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

[patterns.paren]

## Grouped patterns

[patterns.paren.syntax]

Syntax
GroupedPattern → ( Pattern )

[patterns.paren.intro]

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.

    #![allow(unused)]
    fn main() {
    let int_reference = &3;
    match int_reference {
        &(0..=5) => (),
        _ => (),
    }
    }

[patterns.slice]

## Slice patterns

[patterns.slice.syntax]

Syntax
SlicePattern → [ SlicePatternItems? ]

SlicePatternItems → Pattern ( , Pattern )* ,?

[patterns.slice.intro]

Slice patterns can match both arrays of fixed size and slices of dynamic size.

    #![allow(unused)]
    fn main() {
    // Fixed size
    let arr = [1, 2, 3];
    match arr {
        [1, _, _] => "starts with one",
        [a, b, c] => "starts with something else",
    };
    }

    #![allow(unused)]
    fn main() {
    // 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 */ }
    };
    }

[patterns.slice.refutable-array]

Slice patterns are irrefutable when matching an array as long as each element is irrefutable.

[patterns.slice.refutable-slice]

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.

[patterns.slice.restriction]

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.

[patterns.path]

## Path patterns

[patterns.path.syntax]

Syntax
PathPattern → PathExpression

[patterns.path.intro]

Path patterns are patterns that refer either to constant values or to structs or enum variants that have no fields.

[patterns.path.unqualified]

Unqualified path patterns can refer to:

- enum variants
- structs
- constants
- associated constants

[patterns.path.qualified]

Qualified path patterns can only refer to associated constants.

[patterns.path.refutable]

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.

[patterns.const]

### Constant patterns

[patterns.const.partial-eq]

When a constant `C` of type `T` is used as a pattern, we first check that `T: PartialEq`.

[patterns.const.structural-equality]

Furthermore we require that the value of `C` has (recursive) structural equality, which is defined recursively as follows:

[patterns.const.primitive]

- Integers as well as `str`, `bool` and `char` values always have structural equality.

[patterns.const.builtin-aggregate]

- Tuples, arrays, and slices have structural equality if all their fields/elements have structural equality. (In particular, `()` and `[]` always have structural equality.)

[patterns.const.ref]

- References have structural equality if the value they point to has structural equality.

[patterns.const.aggregate]

- 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.

[patterns.const.pointer]

- A raw pointer has structural equality if it was defined as a constant integer (and then cast/transmuted).

[patterns.const.float]

- A float value has structural equality if it is not a `NaN`.

[patterns.const.exhaustive]

- Nothing else has structural equality.

[patterns.const.generic]

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.

[patterns.const.immutable]

The value of `C` must not contain any references to mutable statics (`static mut` items or interior mutable `static` items) or `extern` statics.

[patterns.const.translation]

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.or]

## 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).

[patterns.constraints]

### Static semantics

[patterns.constraints.pattern]

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.

[patterns.constraints.match-type-check]

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`.

[patterns.constraints.exhaustiveness-or-pattern]

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.

[patterns.behavior]

### Dynamic semantics

[patterns.behavior.nested-or-patterns]

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)`.

[patterns.precedence]

### 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.

1. The ObsoleteRangePattern syntax has been removed in the 2021 edition. ↩

# Type system

[type]

# Types

[type.intro]

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.

[type.builtin]

Built-in types are tightly integrated into the language, in nontrivial ways that are not possible to emulate in user-defined types.

[type.user-defined]

User-defined types have limited capabilities.

[type.kinds]

The list of types is:

- Primitive types:
  - Boolean — `bool`
  - Numeric — integer and float
  - Textual — `char` and `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

[type.name]

## Type expressions

[type.name.syntax]

Syntax
Type →
TypeNoBounds
| ImplTraitType
| TraitObjectType

TypeNoBounds →
ParenthesizedType
| ImplTraitTypeOneBound
| TraitObjectTypeOneBound
| TypePath
| TupleType
| NeverType
| RawPointerType
| ReferenceType
| ArrayType
| SliceType
| InferredType
| QualifiedPathInType
| BareFunctionType
| MacroInvocation

[type.name.intro]

A type expression as defined in the Type grammar rule above is the syntax for referring to a type. It may refer to:

[type.name.sequence]

- Sequence types (tuple, array, slice).

[type.name.path]

- Type paths which can reference:
  - Primitive types (boolean, numeric, textual).
  - Paths to an item (struct, enum, union, type alias, trait).
  - `Self` path where `Self` is the implementing type.
  - Generic type parameters.

[type.name.pointer]

- Pointer types (reference, raw pointer, function pointer).

[type.name.inference]

- The inferred type which asks the compiler to determine the type.

[type.name.grouped]

- Parentheses which are used for disambiguation.

[type.name.trait]

- Trait types: Trait objects and impl trait.

[type.name.never]

- The never type.

[type.name.macro-expansion]

- Macros which expand to a type expression.

[type.name.parenthesized]

### Parenthesized types

[type.name.parenthesized.syntax]

Syntax
ParenthesizedType → ( Type )

[type.name.parenthesized.intro]

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.

    #![allow(unused)]
    fn main() {
    use std::any::Any;
    type T<'a> = &'a (dyn Any + Send);
    }

[type.recursive]

## Recursive types

[type.recursive.intro]

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.

[type.recursive.constraint]

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:

    #![allow(unused)]
    fn main() {
    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))));
    }

[type.bool]

# Boolean type

    #![allow(unused)]
    fn main() {
    let b: bool = true;
    }

[type.bool.intro]

The boolean type or bool is a primitive data type that can take on one of two values, called true and false.

[type.bool.literal]

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.

[type.bool.namespace]

This type is a part of the language prelude with the name `bool`.

[type.bool.layout]

An object with the boolean type has a size and alignment of 1 each.

[type.bool.repr]

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.

[type.bool.usage]

The boolean type is the type of many operands in various expressions:

[type.bool.usage-condition]

- The condition operand in if expressions and while expressions

[type.bool.usage-lazy-operator]

- The operands in lazy boolean operator expressions

> Note

> 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`).

[type.bool.traits]

Like all primitives, the boolean type implements the traits `Clone`, `Copy`, `Sized`, `Send`, and `Sync`.

> Note

> See the standard library docs for library operations.

[type.bool.expr]

## Operations on boolean values

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

[type.bool.expr.not]

### Logical not

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

[type.bool.expr.or]

### Logical or

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

[type.bool.expr.and]

### Logical and

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

[type.bool.expr.xor]

### Logical xor

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

[type.bool.expr.cmp]

### Comparisons

[type.bool.expr.cmp.eq]

`a` | `b` | `a == b`
--- | --- | ---
`true` | `true` | `true`
`true` | `false` | `false`
`false` | `true` | `false`
`false` | `false` | `true`

[type.bool.expr.cmp.greater]

`a` | `b` | `a > b`
--- | --- | ---
`true` | `true` | `false`
`true` | `false` | `true`
`false` | `true` | `false`
`false` | `false` | `false`

[type.bool.expr.cmp.not-eq]

- `a != b` is the same as `!(a == b)`

[type.bool.expr.cmp.greater-eq]

- `a >= b` is the same as `a == b | a > b`

[type.bool.expr.cmp.less]

- `a < b` is the same as `!(a >= b)`

[type.bool.expr.cmp.less-eq]

- `a <= b` is the same as `a == b | a < b`

[type.bool.validity]

## 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).

[type.numeric]

# Numeric types

[type.numeric.int]

## Integer types

[type.numeric.int.unsigned]

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

[type.numeric.int.signed]

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

[type.numeric.float]

## Floating-point types

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

[type.numeric.int.size]

## Machine-dependent integer types

[type.numeric.int.size.usize]

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.

> Note

> 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.

[type.numeric.int.size.isize]

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.

[type.numeric.int.size.minimum]

`usize` and `isize` are at least 16-bits wide.

> Note

> 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.

[type.numeric.validity]

## 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`.

[type.text]

# Textual types

[type.text.intro]

The types `char` and `str` hold textual data.

[type.text.char-value]

A value of type `char` is a Unicode scalar value (i.e. a code point that is not a surrogate), represented as a 32-bit unsigned word in the 0x0000 to 0xD7FF or 0xE000 to 0x10FFFF range.

[type.text.char-precondition]

It is immediate undefined behavior to create a `char` that falls outside this range. A `[char]` is effectively a UCS-4 / UTF-32 string of length 1.

[type.text.str-value]

A value of type `str` is represented the same way as `[u8]`, a slice of 8-bit unsigned bytes. However, the Rust standard library makes extra assumptions about `str`: methods working on `str` assume and ensure that the data in there is valid UTF-8. Calling a `str` method with a non-UTF-8 buffer can cause undefined behavior now or in the future.

[type.text.str-unsized]

Since `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]`.

[type.text.layout]

## Layout and bit validity

[type.layout.char-layout]

`char` is guaranteed to have the same size and alignment as `u32` on all platforms.

[type.layout.char-validity]

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).

[type.never]

# Never type

[type.never.syntax]

Syntax
NeverType → !

[type.never.intro]

The never type `!` is a type with no values, representing the result of computations that never complete.

[type.never.coercion]

Expressions of type `!` can be coerced into any other type.

[type.never.constraint]

The `!` type can only appear in function return types presently, indicating it is a diverging function that never returns.

    #![allow(unused)]
    fn main() {
    fn foo() -> ! {
        panic!("This call never returns.");
    }
    }

    #![allow(unused)]
    fn main() {
    unsafe extern "C" {
        pub safe fn no_return_extern_func() -> !;
    }
    }

[type.tuple]

# Tuple types

[type.tuple.syntax]

Syntax
TupleType →
( )
| ( ( Type , )+ Type? )

[type.tuple.intro]

Tuple types are a family of structural types1 for heterogeneous lists of other types.

The syntax for a tuple type is a parenthesized, comma-separated list of types.

[type.tuple.restriction]

1-ary tuples require a comma after their element type to be disambiguated with a parenthesized type.

[type.tuple.field-number]

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.

[type.tuple.field-name]

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.

[type.tuple.unit]

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>)`

[type.tuple.constructor]

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.

[type.tuple.access]

Tuple fields can be accessed by either a tuple index expression or pattern matching.

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

[type.array]

# Array types

[type.array.syntax]

Syntax
ArrayType → [ Type ; Expression ]

[type.array.intro]

An array is a fixed-size sequence of `N` elements of type `T`. The array type is written as `[T; N]`.

[type.array.constraint]

The size is a constant expression that evaluates to a `usize`.

Examples:

    #![allow(unused)]
    fn main() {
    // 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]);
    }

[type.array.index]

All elements of arrays are always initialized, and access to an array is always bounds-checked in safe methods and operators.

> Note

> The `Vec<T>` standard library type provides a heap-allocated resizable array type.

[type.slice]

# Slice types

[type.slice.syntax]

Syntax
SliceType → [ Type ]

[type.slice.intro]

A slice is a dynamically sized type representing a ‘view’ into a sequence of elements of type `T`. The slice type is written as `[T]`.

[type.slice.unsized]

Slice types are generally used through pointer types. For example:

- `&[T]`: a ‘shared slice’, often just called a ‘slice’. It doesn’t own the data it points to; it borrows it.
- `&mut [T]`: a ‘mutable slice’. It mutably borrows the data it points to.
- `Box<[T]>`: a ‘boxed slice’

Examples:

    #![allow(unused)]
    fn main() {
    // A heap-allocated array, coerced to a slice
    let boxed_array: Box<[i32]> = Box::new([1, 2, 3]);

    // A (shared) slice into an array
    let slice: &[i32] = &boxed_array[..];
    }

[type.slice.safe]

All elements of slices are always initialized, and access to a slice is always bounds-checked in safe methods and operators.

[type.struct]

# Struct types

[type.struct.intro]

A `struct` type is a heterogeneous product of other types, called the fields of the type.1

[type.struct.constructor]

New instances of a `struct` can be constructed with a struct expression.

[type.struct.layout]

The memory layout of a `struct` is undefined by default to allow for compiler optimizations like field reordering, but it can be fixed with the `repr` attribute. In either case, fields may be given in any order in a corresponding struct expression; the resulting `struct` value will always have the same memory layout.

[type.struct.field-visibility]

The fields of a `struct` may be qualified by visibility modifiers, to allow access to data in a struct outside a module.

[type.struct.tuple]

A tuple struct type is just like a struct type, except that the fields are anonymous.

[type.struct.unit]

A unit-like struct type is like a struct type, except that it has no fields. The one value constructed by the associated struct expression is the only value that inhabits such a type.

1. `struct` types are analogous to `struct` types in C, the record types of the ML family, or the struct types of the Lisp family. ↩

[type.enum]

# Enumerated types

[type.enum.intro]

An enumerated type is a nominal, heterogeneous disjoint union type, denoted by the name of an `enum` item. 1

[type.enum.declaration]

An `enum` item declares both the type and a number of variants, each of which is independently named and has the syntax of a struct, tuple struct or unit-like struct.

[type.enum.constructor]

New instances of an `enum` can be constructed with a struct expression.

[type.enum.value]

Any `enum` value consumes as much memory as the largest variant for its corresponding `enum` type, as well as the size needed to store a discriminant.

[type.enum.name]

Enum types cannot be denoted structurally as types, but must be denoted by named reference to an `enum` item.

1. The `enum` type is analogous to a `data` constructor declaration in Haskell, or a pick ADT in Limbo. ↩

[type.union]

# Union types

[type.union.intro]

A union type is a nominal, heterogeneous C-like union, denoted by the name of a `union` item.

[type.union.access]

Unions have no notion of an “active field”. Instead, every union access transmutes parts of the content of the union to the type of the accessed field.

[type.union.safety]

Since transmutes can cause unexpected or undefined behaviour, `unsafe` is required to read from a union field.

[type.union.constraint]

Union field types are also restricted to a subset of types which ensures that they never need dropping. See the item documentation for further details.

[type.union.layout]

The memory layout of a `union` is undefined by default (in particular, fields do not have to be at offset 0), but the `#[repr(...)]` attribute can be used to fix a layout.

[type.fn-item]

# Function item types

[type.fn-item.intro]

When referred to, a function item, or the constructor of a tuple-like struct or enum variant, yields a zero-sized value of its function item type.

[type.fn-item.unique]

That type explicitly identifies the function - its name, its type arguments, and its early-bound lifetime arguments (but not its late-bound lifetime arguments, which are only assigned when the function is called) - so the value does not need to contain an actual function pointer, and no indirection is needed when the function is called.

[type.fn-item.name]

There is no syntax that directly refers to a function item type, but the compiler will display the type as something like `fn(u32) -> i32 {fn_name}` in error messages.

Because the function item type explicitly identifies the function, the item types of different functions - different items, or the same item with different generics - are distinct, and mixing them will create a type error:

    #![allow(unused)]
    fn main() {
    fn foo<T>() { }
    let x = &mut foo::<i32>;
    *x = foo::<u32>; //~ ERROR mismatched types
    }

[type.fn-item.coercion]

However, there is a coercion from function items to function pointers with the same signature, which is triggered not only when a function item is used when a function pointer is directly expected, but also when different function item types with the same signature meet in different arms of the same `if` or `match`:

    #![allow(unused)]
    fn main() {
    let want_i32 = false;
    fn foo<T>() { }

    // `foo_ptr_1` has function pointer type `fn()` here
    let foo_ptr_1: fn() = foo::<i32>;

    // ... and so does `foo_ptr_2` - this type-checks.
    let foo_ptr_2 = if want_i32 {
        foo::<i32>
    } else {
        foo::<u32>
    };
    }

[type.fn-item.traits]

All function items implement `Copy`, `Clone`, `Send`, and `Sync`.

`Fn`, `FnMut`, and `FnOnce` are implemented unless the function has any of the following:

- an `unsafe` qualifier
- a `target_feature` attribute
- an ABI other than `"Rust"`

[type.closure]

# Closure types

[type.closure.intro]

A closure expression produces a closure value with a unique, anonymous type that cannot be written out. A closure type is approximately equivalent to a struct which contains the captured values. For instance, the following closure:

    #![allow(unused)]
    fn main() {
    #[derive(Debug)]
    struct Point { x: i32, y: i32 }
    struct Rectangle { left_top: Point, right_bottom: Point }

    fn f<F : FnOnce() -> String> (g: F) {
        println!("{}", g());
    }

    let mut rect = Rectangle {
        left_top: Point { x: 1, y: 1 },
        right_bottom: Point { x: 0, y: 0 }
    };

    let c = || {
        rect.left_top.x += 1;
        rect.right_bottom.x += 1;
        format!("{:?}", rect.left_top)
    };
    f(c); // Prints "Point { x: 2, y: 1 }".
    }

generates a closure type roughly like the following:

    // Note: This is not exactly how it is translated, this is only for
    // illustration.

    struct Closure<'a> {
        left_top : &'a mut Point,
        right_bottom_x : &'a mut i32,
    }

    impl<'a> FnOnce<()> for Closure<'a> {
        type Output = String;
        extern "rust-call" fn call_once(self, args: ()) -> String {
            self.left_top.x += 1;
            *self.right_bottom_x += 1;
            format!("{:?}", self.left_top)
        }
    }

so that the call to `f` works as if it were:

    f(Closure{ left_top: &mut rect.left_top, right_bottom_x: &mut rect.right_bottom.x });

[type.closure.capture]

## Capture modes

[type.closure.capture.intro]

A capture mode determines how a place expression from the environment is borrowed or moved into the closure. The capture modes are:

1. Immutable borrow (`ImmBorrow`) — The place expression is captured as a shared reference.
2. Unique immutable borrow (`UniqueImmBorrow`) — This is similar to an immutable borrow, but must be unique as described below.
3. Mutable borrow (`MutBorrow`) — The place expression is captured as a mutable reference.
4. Move (`ByValue`) — The place expression is captured by moving the value into the closure.

[type.closure.capture.precedence]

Place expressions from the environment are captured from the first mode that is compatible with how the captured value is used inside the closure body. The mode is not affected by the code surrounding the closure, such as the lifetimes of involved variables or fields, or of the closure itself.

[type.closure.capture.copy]

### `Copy` values

Values that implement `Copy` that are moved into the closure are captured with the `ImmBorrow` mode.

    #![allow(unused)]
    fn main() {
    let x = [0; 1024];
    let c = || {
        let y = x; // x captured by ImmBorrow
    };
    }

[type.closure.async.input]

### Async input capture

Async closures always capture all input arguments, regardless of whether or not they are used within the body.

## Capture precision

[type.closure.capture.precision.capture-path]

A capture path is a sequence starting with a variable from the environment followed by zero or more place projections from that variable.

[type.closure.capture.precision.place-projection]

A place projection is a field access, tuple index, dereference (and automatic dereferences), array or slice index expression, or pattern destructuring applied to a variable.

> Note

> In `rustc`, pattern destructuring desugars into a series of dereferences and field or element accesses.

[type.closure.capture.precision.intro]

The closure borrows or moves the capture path, which may be truncated based on the rules described below.

For example:

    #![allow(unused)]
    fn main() {
    struct SomeStruct {
        f1: (i32, i32),
    }
    let s = SomeStruct { f1: (1, 2) };

    let c = || {
        let x = s.f1.1; // s.f1.1 captured by ImmBorrow
    };
    c();
    }

Here the capture path is the local variable `s`, followed by a field access `.f1`, and then a tuple index `.1`. This closure captures an immutable borrow of `s.f1.1`.

[type.closure.capture.precision.shared-prefix]

### Shared prefix

In the case where a capture path and one of the ancestors of that path are both captured by a closure, the ancestor path is captured with the highest capture mode among the two captures, `CaptureMode = max(AncestorCaptureMode, DescendantCaptureMode)`, using the strict weak ordering:

`ImmBorrow < UniqueImmBorrow < MutBorrow < ByValue`

Note that this might need to be applied recursively.

    #![allow(unused)]
    fn main() {
    // In this example, there are three different capture paths with a shared ancestor:
    fn move_value<T>(_: T){}
    let s = String::from("S");
    let t = (s, String::from("T"));
    let mut u = (t, String::from("U"));

    let c = || {
        println!("{:?}", u); // u captured by ImmBorrow
        u.1.truncate(0); // u.0 captured by MutBorrow
        move_value(u.0.0); // u.0.0 captured by ByValue
    };
    c();
    }

Overall this closure will capture `u` by `ByValue`.

[type.closure.capture.precision.dereference-shared]

### Rightmost shared reference truncation

The capture path is truncated at the rightmost dereference in the capture path if the dereference is applied to a shared reference.

This truncation is allowed because fields that are read through a shared reference will always be read via a shared reference or a copy. This helps reduce the size of the capture when the extra precision does not yield any benefit from a borrow checking perspective.

The reason it is the rightmost dereference is to help avoid a shorter lifetime than is necessary. Consider the following example:

    #![allow(unused)]
    fn main() {
    struct Int(i32);
    struct B<'a>(&'a i32);

    struct MyStruct<'a> {
       a: &'static Int,
       b: B<'a>,
    }

    fn foo<'a, 'b>(m: &'a MyStruct<'b>) -> impl FnMut() + 'static {
        let c = || drop(&m.a.0);
        c
    }
    }

If this were to capture `m`, then the closure would no longer outlive `'static`, since `m` is constrained to `'a`. Instead, it captures `(*(*m).a)` by `ImmBorrow`.

[type.closure.capture.precision.wildcard]

### Wildcard pattern bindings

[type.closure.capture.precision.wildcard.reads]

Closures only capture data that needs to be read. Binding a value with a wildcard pattern does not read the value, so the place is not captured.

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.
    let x = S;
    let c = || {
        let _ = x;  // Does not capture `x`.
    };
    let c = || match x {
        _ => (), // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();
    }

[type.closure.capture.precision.wildcard.destructuring]

Destructuring tuples, structs, and single-variant enums does not, by itself, cause a read or the place to be captured.

> Note

> Enums marked with `#[non_exhaustive]` from other crates are always treated as having multiple variants. See type.closure.capture.precision.discriminants.non_exhaustive.

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.

    // Destructuring tuples does not cause a read or capture.
    let x = (S,);
    let c = || {
        let (..) = x; // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();

    // Destructuring unit structs does not cause a read or capture.
    let x = S;
    let c = || {
        let S = x; // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();

    // Destructuring structs does not cause a read or capture.
    struct W<T>(T);
    let x = W(S);
    let c = || {
        let W(..) = x; // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();

    // Destructuring single-variant enums does not cause a read
    // or capture.
    enum E<T> { V(T) }
    let x = E::V(S);
    let c = || {
        let E::V(..) = x; // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();
    }

[type.closure.capture.precision.wildcard.fields]

Fields matched against RestPattern (`..`) or StructPatternEtCetera (also `..`) are not read, and those fields are not captured.

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.
    let x = (S, S);
    let c = || {
        let (x0, ..) = x;  // Captures `x.0` by `ByValue`.
    };
    // Only the first tuple field was captured by the closure.
    x.1; // OK: `x.1` can be moved here.
    c();
    }

[type.closure.capture.precision.wildcard.array-slice]

Partial captures of arrays and slices are not supported; the entire slice or array is always captured even if used with wildcard pattern matching, indexing, or sub-slicing.

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.
    let mut x = [S, S];
    let c = || {
        let [x0, _] = x; // Captures all of `x` by `ByValue`.
    };
    let _ = &mut x[1]; // ERROR: Borrow of moved value.
    }

[type.closure.capture.precision.wildcard.initialized]

Values that are matched with wildcards must still be initialized.

    #![allow(unused)]
    fn main() {
    let x: u8;
    let c = || {
        let _ = x; // ERROR: Binding `x` isn't initialized.
    };
    }

[type.closure.capture.precision.discriminants]

### Capturing for discriminant reads

[type.closure.capture.precision.discriminants.reads]

If pattern matching reads a discriminant, the place containing that discriminant is captured by `ImmBorrow`.

[type.closure.capture.precision.discriminants.multiple-variant]

Matching against a variant of an enum that has more than one variant reads the discriminant, capturing the place by `ImmBorrow`.

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.
    let mut x = (Some(S), S);
    let c = || match x {
        (None, _) => (),
    //   ^^^^
    // This pattern requires reading the discriminant, which
    // causes `x.0` to be captured by `ImmBorrow`.
        _ => (),
    };
    let _ = &mut x.0; // ERROR: Cannot borrow `x.0` as mutable.
    //           ^^^
    // The closure is still live, so `x.0` is still immutably
    // borrowed here.
    c();
    }

    #![allow(unused)]
    fn main() {
    struct S; // A non-`Copy` type.
    let x = (Some(S), S);
    let c = || match x { // Captures `x.0` by `ImmBorrow`.
        (None, _) => (),
        _ => (),
    };
    // Though `x.0` is captured due to the discriminant read,
    // `x.1` is not captured.
    x.1; // OK: `x.1` can be moved here.
    c();
    }

[type.closure.capture.precision.discriminants.single-variant]

Matching against the only variant of a single-variant enum does not read the discriminant and does not capture the place.

    #![allow(unused)]
    fn main() {
    enum E<T> { V(T) } // A single-variant enum.
    let x = E::V(());
    let c = || {
        let E::V(_) = x; // Does not capture `x`.
    };
    x; // OK: `x` can be moved here.
    c();
    }

[type.closure.capture.precision.discriminants.non_exhaustive]

If `#[non_exhaustive]` is applied to an enum defined in an external crate, the enum is treated as having multiple variants for the purpose of deciding whether a read occurs, even if it actually has only one variant.

[type.closure.capture.precision.discriminants.uninhabited-variants]

Even if all variants but the one being matched against are uninhabited, making the pattern irrefutable, the discriminant is still read if it otherwise would be.

    #![allow(unused)]
    fn main() {
    enum Empty {}
    let mut x = Ok::<_, Empty>(42);
    let c = || {
        let Ok(_) = x; // Captures `x` by `ImmBorrow`.
    };
    let _ = &mut x; // ERROR: Cannot borrow `x` as mutable.
    c();
    }

[type.closure.capture.precision.range-patterns]

### Capturing and range patterns

[type.closure.capture.precision.range-patterns.reads]

Matching against a range pattern reads the place being matched, even if the range includes all possible values of the type, and captures the place by `ImmBorrow`.

    #![allow(unused)]
    fn main() {
    let mut x = 0u8;
    let c = || {
        let 0..=u8::MAX = x; // Captures `x` by `ImmBorrow`.
    };
    let _ = &mut x; // ERROR: Cannot borrow `x` as mutable.
    c();
    }

[type.closure.capture.precision.slice-patterns]

### Capturing and slice patterns

[type.closure.capture.precision.slice-patterns.slices]

Matching a slice against a slice pattern other than one with only a single rest pattern (i.e. `[..]`) is treated as a read of the length from the slice and captures the slice by `ImmBorrow`.

    #![allow(unused)]
    fn main() {
    let x: &mut [u8] = &mut [];
    let c = || match x { // Captures `*x` by `ImmBorrow`.
        &mut [] => (),
    //       ^^
    // This matches a slice of exactly zero elements. To know whether the
    // scrutinee matches, the length must be read, causing the slice to
    // be captured.
        _ => (),
    };
    let _ = &mut *x; // ERROR: Cannot borrow `*x` as mutable.
    c();
    }

    #![allow(unused)]
    fn main() {
    let x: &mut [u8] = &mut [];
    let c = || match x { // Does not capture `*x`.
        [..] => (),
    //   ^^ Rest pattern.
    };
    let _ = &mut *x; // OK: `*x` can be borrow here.
    c();
    }

> Note

> Perhaps surprisingly, even though the length is contained in the (wide) pointer to the slice, it is the place of the pointee (the slice) that is treated as read and is captured.

>     #![allow(unused)]
>     fn main() {
>     fn f<'l: 's, 's>(x: &'s mut &'l [u8]) -> impl Fn() + 'l {
>         // The closure outlives `'l` because it captures `**x`. If
>         // instead it captured `*x`, it would not live long enough
>         // to satisfy the `impl Fn() + 'l` bound.
>         || match *x { // Captures `**x` by `ImmBorrow`.
>             &[] => (),
>             _ => (),
>         }
>     }
>     }

> In this way, the behavior is consistent with dereferencing to the slice in the scrutinee.

>     #![allow(unused)]
>     fn main() {
>     fn f<'l: 's, 's>(x: &'s mut &'l [u8]) -> impl Fn() + 'l {
>         || match **x { // Captures `**x` by `ImmBorrow`.
>             [] => (),
>             _ => (),
>         }
>     }
>     }

> For details, see Rust PR #138961.

[type.closure.capture.precision.slice-patterns.arrays]

As the length of an array is fixed by its type, matching an array against a slice pattern does not by itself capture the place.

    #![allow(unused)]
    fn main() {
    let x: [u8; 1] = [0];
    let c = || match x { // Does not capture `x`.
        [_] => (), // Length is fixed.
    };
    x; // OK: `x` can be moved here.
    c();
    }

[type.closure.capture.precision.move-dereference]

### Capturing references in move contexts

Because it is not allowed to move fields out of a reference, `move` closures will only capture the prefix of a capture path that runs up to, but not including, the first dereference of a reference. The reference itself will be moved into the closure.

    #![allow(unused)]
    fn main() {
    struct T(String, String);

    let mut t = T(String::from("foo"), String::from("bar"));
    let t_mut_ref = &mut t;
    let mut c = move || {
        t_mut_ref.0.push_str("123"); // captures `t_mut_ref` ByValue
    };
    c();
    }

[type.closure.capture.precision.raw-pointer-dereference]

### Raw pointer dereference

Because it is `unsafe` to dereference a raw pointer, closures will only capture the prefix of a capture path that runs up to, but not including, the first dereference of a raw pointer.

    #![allow(unused)]
    fn main() {
    struct T(String, String);

    let t = T(String::from("foo"), String::from("bar"));
    let t_ptr = &t as *const T;

    let c = || unsafe {
        println!("{}", (*t_ptr).0); // captures `t_ptr` by ImmBorrow
    };
    c();
    }

[type.closure.capture.precision.union]

### Union fields

Because it is `unsafe` to access a union field, closures will only capture the prefix of a capture path that runs up to the union itself.

    #![allow(unused)]
    fn main() {
    union U {
        a: (i32, i32),
        b: bool,
    }
    let u = U { a: (123, 456) };

    let c = || {
        let x = unsafe { u.a.0 }; // captures `u` ByValue
    };
    c();

    // This also includes writing to fields.
    let mut u = U { a: (123, 456) };

    let mut c = || {
        u.b = true; // captures `u` with MutBorrow
    };
    c();
    }

[type.closure.capture.precision.unaligned]

### Reference into unaligned `struct`s

Because it is undefined behavior to create references to unaligned fields in a structure, closures will only capture the prefix of the capture path that runs up to, but not including, the first field access into a structure that uses the `packed` representation. This includes all fields, even those that are aligned, to protect against compatibility concerns should any of the fields in the structure change in the future.

    #![allow(unused)]
    fn main() {
    #[repr(packed)]
    struct T(i32, i32);

    let t = T(2, 5);
    let c = || {
        let a = t.0; // captures `t` with ImmBorrow
    };
    // Copies out of `t` are ok.
    let (a, b) = (t.0, t.1);
    c();
    }

Similarly, taking the address of an unaligned field also captures the entire struct:

    #![allow(unused)]
    fn main() {
    #[repr(packed)]
    struct T(String, String);

    let mut t = T(String::new(), String::new());
    let c = || {
        let a = std::ptr::addr_of!(t.1); // captures `t` with ImmBorrow
    };
    let a = t.0; // ERROR: cannot move out of `t.0` because it is borrowed
    c();
    }

but the above works if it is not packed since it captures the field precisely:

    #![allow(unused)]
    fn main() {
    struct T(String, String);

    let mut t = T(String::new(), String::new());
    let c = || {
        let a = std::ptr::addr_of!(t.1); // captures `t.1` with ImmBorrow
    };
    // The move here is allowed.
    let a = t.0;
    c();
    }

[type.closure.capture.precision.box-deref]

### `Box` vs other `Deref` implementations

The implementation of the `Deref` trait for `Box` is treated differently from other `Deref` implementations, as it is considered a special entity.

For example, let us look at examples involving `Rc` and `Box`. The `*rc` is desugared to a call to the trait method `deref` defined on `Rc`, but since `*box` is treated differently, it is possible to do a precise capture of the contents of the `Box`.

[type.closure.capture.precision.box-non-move.not-moved]

#### `Box` with non-`move` closure

In a non-`move` closure, if the contents of the `Box` are not moved into the closure body, the contents of the `Box` are precisely captured.

    #![allow(unused)]
    fn main() {
    struct S(String);

    let b = Box::new(S(String::new()));
    let c_box = || {
        let x = &(*b).0; // captures `(*b).0` by ImmBorrow
    };
    c_box();

    // Contrast `Box` with another type that implements Deref:
    let r = std::rc::Rc::new(S(String::new()));
    let c_rc = || {
        let x = &(*r).0; // captures `r` by ImmBorrow
    };
    c_rc();
    }

[type.closure.capture.precision.box-non-move.moved]

However, if the contents of the `Box` are moved into the closure, then the box is entirely captured. This is done so the amount of data that needs to be moved into the closure is minimized.

    #![allow(unused)]
    fn main() {
    // This is the same as the example above except the closure
    // moves the value instead of taking a reference to it.

    struct S(String);

    let b = Box::new(S(String::new()));
    let c_box = || {
        let x = (*b).0; // captures `b` with ByValue
    };
    c_box();
    }

[type.closure.capture.precision.box-move.read]

#### `Box` with move closure

Similarly to moving contents of a `Box` in a non-`move` closure, reading the contents of a `Box` in a `move` closure will capture the `Box` entirely.

    #![allow(unused)]
    fn main() {
    struct S(i32);

    let b = Box::new(S(10));
    let c_box = move || {
        let x = (*b).0; // captures `b` with ByValue
    };
    }

[type.closure.unique-immutable]

## Unique immutable borrows in captures

Captures can occur by a special kind of borrow called a unique immutable borrow, which cannot be used anywhere else in the language and cannot be written out explicitly. It occurs when modifying the referent of a mutable reference, as in the following example:

    #![allow(unused)]
    fn main() {
    let mut b = false;
    let x = &mut b;
    let mut c = || {
        // An ImmBorrow and a MutBorrow of `x`.
        let a = &x;
        *x = true; // `x` captured by UniqueImmBorrow
    };
    // The following line is an error:
    // let y = &x;
    c();
    // However, the following is OK.
    let z = &x;
    }

In this case, borrowing `x` mutably is not possible, because `x` is not `mut`. But at the same time, borrowing `x` immutably would make the assignment illegal, because a `& &mut` reference might not be unique, so it cannot safely be used to modify a value. So a unique immutable borrow is used: it borrows `x` immutably, but like a mutable borrow, it must be unique.

In the above example, uncommenting the declaration of `y` will produce an error because it would violate the uniqueness of the closure’s borrow of `x`; the declaration of z is valid because the closure’s lifetime has expired at the end of the block, releasing the borrow.

[type.closure.call]

## Call traits and coercions

[type.closure.call.intro]

Closure types all implement `FnOnce`, indicating that they can be called once by consuming ownership of the closure. Additionally, some closures implement more specific call traits:

[type.closure.call.fn-mut]

- A closure which does not move out of any captured variables implements `FnMut`, indicating that it can be called by mutable reference.

[type.closure.call.fn]

- A closure which does not mutate or move out of any captured variables implements `Fn`, indicating that it can be called by shared reference.

> Note

> `move` closures may still implement `Fn` or `FnMut`, even though they capture variables by move. This is because the traits implemented by a closure type are determined by what the closure does with captured values, not how it captures them.

[type.closure.non-capturing]

Non-capturing closures are closures that don’t capture anything from their environment. Non-async, non-capturing closures can be coerced to function pointers (e.g., `fn()`) with the matching signature.

    #![allow(unused)]
    fn main() {
    let add = |x, y| x + y;

    let mut x = add(5,7);

    type Binop = fn(i32, i32) -> i32;
    let bo: Binop = add;
    x = bo(5,7);
    }

[type.closure.async.traits]

### Async closure traits

[type.closure.async.traits.fn-family]

Async closures have a further restriction of whether or not they implement `FnMut` or `Fn`.

The `Future` returned by the async closure has similar capturing characteristics as a closure. It captures place expressions from the async closure based on how they are used. The async closure is said to be lending to its `Future` if it has either of the following properties:

- The `Future` includes a mutable capture.
- The async closure captures by value, except when the value is accessed with a dereference projection.

If the async closure is lending to its `Future`, then `FnMut` and `Fn` are not implemented. `FnOnce` is always implemented.

> Example: The first clause for a mutable capture can be illustrated with the following:

>     #![allow(unused)]
>     fn main() {
>     fn takes_callback<Fut: Future>(c: impl FnMut() -> Fut) {}

>     fn f() {
>         let mut x = 1i32;
>         let c = async || {
>             x = 2;  // x captured with MutBorrow
>         };
>         takes_callback(c);  // ERROR: async closure does not implement `FnMut`
>     }
>     }

> The second clause for a regular value capture can be illustrated with the following:

>     #![allow(unused)]
>     fn main() {
>     fn takes_callback<Fut: Future>(c: impl Fn() -> Fut) {}

>     fn f() {
>         let x = &1i32;
>         let c = async move || {
>             let a = x + 2;  // x captured ByValue
>         };
>         takes_callback(c);  // ERROR: async closure does not implement `Fn`
>     }
>     }

> The exception of the the second clause can be illustrated by using a dereference, which does allow `Fn` and `FnMut` to be implemented:

>     #![allow(unused)]
>     fn main() {
>     fn takes_callback<Fut: Future>(c: impl Fn() -> Fut) {}

>     fn f() {
>         let x = &1i32;
>         let c = async move || {
>             let a = *x + 2;
>         };
>         takes_callback(c);  // OK: implements `Fn`
>     }
>     }

[type.closure.async.traits.async-family]

Async closures implement `AsyncFn`, `AsyncFnMut`, and `AsyncFnOnce` in an analogous way as regular closures implement `Fn`, `FnMut`, and `FnOnce`; that is, depending on the use of the captured variables in its body.

[type.closure.traits]

### Other traits

[type.closure.traits.intro]

All closure types implement `Sized`. Additionally, closure types implement the following traits if allowed to do so by the types of the captures it stores:

- `Clone`
- `Copy`
- `Sync`
- `Send`

[type.closure.traits.behavior]

The rules for `Send` and `Sync` match those for normal struct types, while `Clone` and `Copy` behave as if derived. For `Clone`, the order of cloning of the captured values is left unspecified.

Because captures are often by reference, the following general rules arise:

- A closure is `Sync` if all captured values are `Sync`.
- A closure is `Send` if all values captured by non-unique immutable reference are `Sync`, and all values captured by unique immutable or mutable reference, copy, or move are `Send`.
- A closure is `Clone` or `Copy` if it does not capture any values by unique immutable or mutable reference, and if all values it captures by copy or move are `Clone` or `Copy`, respectively.

[type.closure.drop-order]

## Drop order

If a closure captures a field of a composite types such as structs, tuples, and enums by value, the field’s lifetime would now be tied to the closure. As a result, it is possible for disjoint fields of a composite types to be dropped at different times.

    #![allow(unused)]
    fn main() {
    {
        let tuple =
          (String::from("foo"), String::from("bar")); // --+
        { //                                               |
            let c = || { // ----------------------------+  |
                // tuple.0 is captured into the closure |  |
                drop(tuple.0); //                       |  |
            }; //                                       |  |
        } // 'c' and 'tuple.0' dropped here ------------+  |
    } // tuple.1 dropped here -----------------------------+
    }

[type.closure.capture.precision.edition2018.entirety]

## Edition 2018 and before

### Closure types difference

In Edition 2018 and before, closures always capture a variable in its entirety, without its precise capture path. This means that for the example used in the Closure types section, the generated closure type would instead look something like this:

    struct Closure<'a> {
        rect : &'a mut Rectangle,
    }

    impl<'a> FnOnce<()> for Closure<'a> {
        type Output = String;
        extern "rust-call" fn call_once(self, args: ()) -> String {
            self.rect.left_top.x += 1;
            self.rect.right_bottom.x += 1;
            format!("{:?}", self.rect.left_top)
        }
    }

and the call to `f` would work as follows:

    f(Closure { rect: rect });

[type.closure.capture.precision.edition2018.composite]

### Capture precision difference

Composite types such as structs, tuples, and enums are always captured in its entirety, not by individual fields. As a result, it may be necessary to borrow into a local variable in order to capture a single field:

    #![allow(unused)]
    fn main() {
    use std::collections::HashSet;

    struct SetVec {
        set: HashSet<u32>,
        vec: Vec<u32>
    }

    impl SetVec {
        fn populate(&mut self) {
            let vec = &mut self.vec;
            self.set.iter().for_each(|&n| {
                vec.push(n);
            })
        }
    }
    }

If, instead, the closure were to use `self.vec` directly, then it would attempt to capture `self` by mutable reference. But since `self.set` is already borrowed to iterate over, the code would not compile.

[type.closure.capture.precision.edition2018.move]

If the `move` keyword is used, then all captures are by move or, for `Copy` types, by copy, regardless of whether a borrow would work. The `move` keyword is usually used to allow the closure to outlive the captured values, such as if the closure is being returned or used to spawn a new thread.

[type.closure.capture.precision.edition2018.wildcard]

Regardless of if the data will be read by the closure, i.e. in case of wild card patterns, if a variable defined outside the closure is mentioned within the closure the variable will be captured in its entirety.

[type.closure.capture.precision.edition2018.drop-order]

### Drop order difference

As composite types are captured in their entirety, a closure which captures one of those composite types by value would drop the entire captured variable at the same time as the closure gets dropped.

    #![allow(unused)]
    fn main() {
    {
        let tuple =
          (String::from("foo"), String::from("bar"));
        {
            let c = || { // --------------------------+
                // tuple is captured into the closure |
                drop(tuple.0); //                     |
            }; //                                     |
        } // 'c' and 'tuple' dropped here ------------+
    }
    }

[type.pointer]

# Pointer types

[type.pointer.intro]

All pointers are explicit first-class values. They can be moved or copied, stored into data structs, and returned from functions.

[type.pointer.reference]

## References (`&` and `&mut`)

[type.pointer.reference.syntax]

Syntax
ReferenceType → & Lifetime? mut? TypeNoBounds

[type.pointer.reference.shared]

### Shared references (`&`)

[type.pointer.reference.shared.intro]

Shared references point to memory which is owned by some other value.

[type.pointer.reference.shared.constraint-mutation]

When a shared reference to a value is created, it prevents direct mutation of the value. Interior mutability provides an exception for this in certain circumstances. As the name suggests, any number of shared references to a value may exist. A shared reference type is written `&type`, or `&'a type` when you need to specify an explicit lifetime.

[type.pointer.reference.shared.copy]

Copying a reference is a “shallow” operation: it involves only copying the pointer itself, that is, pointers are `Copy`. Releasing a reference has no effect on the value it points to, but referencing of a temporary value will keep it alive during the scope of the reference itself.

[type.pointer.reference.mut]

### Mutable references (`&mut`)

[type.pointer.reference.mut.intro]

Mutable references point to memory which is owned by some other value. A mutable reference type is written `&mut type` or `&'a mut type`.

[type.pointer.reference.mut.copy]

A mutable reference (that hasn’t been borrowed) is the only way to access the value it points to, so is not `Copy`.

[type.pointer.raw]

## Raw pointers (`*const` and `*mut`)

[type.pointer.raw.syntax]

Syntax
RawPointerType → * ( mut | const ) TypeNoBounds

[type.pointer.raw.intro]

Raw pointers are pointers without safety or liveness guarantees. Raw pointers are written as `*const T` or `*mut T`. For example `*const i32` means a raw pointer to a 32-bit integer.

[type.pointer.raw.copy]

Copying or dropping a raw pointer has no effect on the lifecycle of any other value.

[type.pointer.raw.safety]

Dereferencing a raw pointer is an `unsafe` operation.

This can also be used to convert a raw pointer to a reference by reborrowing it (`&*` or `&mut *`). Raw pointers are generally discouraged; they exist to support interoperability with foreign code, and writing performance-critical or low-level functions.

[type.pointer.raw.cmp]

When comparing raw pointers they are compared by their address, rather than by what they point to. When comparing raw pointers to dynamically sized types they also have their additional data compared.

[type.pointer.raw.constructor]

Raw pointers can be created directly using `&raw const` for `*const` pointers and `&raw mut` for `*mut` pointers.

[type.pointer.smart]

## Smart pointers

The standard library contains additional ‘smart pointer’ types beyond references and raw pointers.

[type.pointer.validity]

## Bit validity

[type.pointer.validity.pointer-fragment]

Despite pointers and references being similar to `usize`s in the machine code emitted on most platforms, the semantics of transmuting a reference or pointer type to a non-pointer type is currently undecided. Thus, it may not be valid to transmute a pointer or reference type, `P`, to a `[u8; size_of::<P>()]`.

[type.pointer.validity.raw]

For thin raw pointers (i.e., for `P = *const T` or `P = *mut T` for `T: Sized`), the inverse direction (transmuting from an integer or array of integers to `P`) is always valid. However, the pointer produced via such a transmutation may not be dereferenced (not even if `T` has size zero).

[type.fn-pointer]

# Function pointer types

[type.fn-pointer.syntax]

Syntax
BareFunctionType →
ForLifetimes? FunctionTypeQualifiers fn
( FunctionParametersMaybeNamedVariadic? ) BareFunctionReturnType?

FunctionTypeQualifiers → unsafe? ( extern Abi? )?

BareFunctionReturnType → -> TypeNoBounds

FunctionParametersMaybeNamedVariadic →
MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadic

MaybeNamedFunctionParameters →
MaybeNamedParam ( , MaybeNamedParam )* ,?

MaybeNamedParam →
OuterAttribute* ( ( IDENTIFIER | _ ) : )? Type

MaybeNamedFunctionParametersVariadic →
( MaybeNamedParam , )* MaybeNamedParam , OuterAttribute* ...

[type.fn-pointer.intro]

A function pointer type, written using the `fn` keyword, refers to a function whose identity is not necessarily known at compile-time.

An example where `Binop` is defined as a function pointer type:

    #![allow(unused)]
    fn main() {
    fn add(x: i32, y: i32) -> i32 {
        x + y
    }

    let mut x = add(5,7);

    type Binop = fn(i32, i32) -> i32;
    let bo: Binop = add;
    x = bo(5,7);
    }

[type.fn-pointer.coercion]

Function pointers can be created via a coercion from both function items and non-capturing, non-async closures.

[type.fn-pointer.qualifiers]

The `unsafe` qualifier indicates that the type’s value is an unsafe function, and the `extern` qualifier indicates it is an extern function.

[type.fn-pointer.constraint-variadic]

For the function to be variadic, its `extern` ABI must be one of those listed in items.extern.variadic.conventions.

[type.fn-pointer.attributes]

## Attributes on function pointer parameters

Attributes on function pointer parameters follow the same rules and restrictions as regular function parameters.

[type.trait-object]

# Trait objects

[type.trait-object.syntax]

Syntax
TraitObjectType → dyn? TypeParamBounds

TraitObjectTypeOneBound → dyn? TraitBound

[type.trait-object.intro]

A trait object is an opaque value of another type that implements a set of traits. The set of traits is made up of a dyn compatible base trait plus any number of auto traits.

[type.trait-object.impls]

Trait objects implement the base trait, its auto traits, and any supertraits of the base trait.

[type.trait-object.name]

Trait objects are written as the keyword `dyn` followed by a set of trait bounds, but with the following restrictions on the trait bounds.

[type.trait-object.constraint]

There may not be more than one non-auto trait, no more than one lifetime, and opt-out bounds (e.g. `?Sized`) are not allowed. Furthermore, paths to traits may be parenthesized.

For example, given a trait `Trait`, the following are all trait objects:

- `dyn Trait`
- `dyn Trait + Send`
- `dyn Trait + Send + Sync`
- `dyn Trait + 'static`
- `dyn Trait + Send + 'static`
- `dyn Trait +`
- `dyn 'static + Trait`.
- `dyn (Trait)`

[type.trait-object.syntax-edition2021]

> 2021 Edition differences

> Before the 2021 edition, the `dyn` keyword may be omitted.

[type.trait-object.syntax-edition2018]

> 2018 Edition differences

> In the 2015 edition, if the first bound of the trait object is a path that starts with `::`, then the `dyn` will be treated as a part of the path. The first path can be put in parenthesis to get around this. As such, if you want a trait object with the trait `::your_module::Trait`, you should write it as `dyn (::your_module::Trait)`.

> Beginning in the 2018 edition, `dyn` is a true keyword and is not allowed in paths, so the parentheses are not necessary.

[type.trait-object.alias]

Two trait object types alias each other if the base traits alias each other and if the sets of auto traits are the same and the lifetime bounds are the same. For example, `dyn Trait + Send + UnwindSafe` is the same as `dyn Trait + UnwindSafe + Send`.

[type.trait-object.unsized]

Due to the opaqueness of which concrete type the value is of, trait objects are dynamically sized types. Like all DSTs, trait objects are used behind some type of pointer; for example `&dyn SomeTrait` or `Box<dyn SomeTrait>`. Each instance of a pointer to a trait object includes:

- a pointer to an instance of a type `T` that implements `SomeTrait`
- a virtual method table, often just called a vtable, which contains, for each method of `SomeTrait` and its supertraits that `T` implements, a pointer to `T`’s implementation (i.e. a function pointer).

The purpose of trait objects is to permit “late binding” of methods. Calling a method on a trait object results in virtual dispatch at runtime: that is, a function pointer is loaded from the trait object vtable and invoked indirectly. The actual implementation for each vtable entry can vary on an object-by-object basis.

An example of a trait object:

    trait Printable {
        fn stringify(&self) -> String;
    }

    impl Printable for i32 {
        fn stringify(&self) -> String { self.to_string() }
    }

    fn print(a: Box<dyn Printable>) {
        println!("{}", a.stringify());
    }

    fn main() {
        print(Box::new(10) as Box<dyn Printable>);
    }

In this example, the trait `Printable` occurs as a trait object in both the type signature of `print`, and the cast expression in `main`.

[type.trait-object.lifetime-bounds]

## Trait object lifetime bounds

Since a trait object can contain references, the lifetimes of those references need to be expressed as part of the trait object. This lifetime is written as `Trait + 'a`. There are defaults that allow this lifetime to usually be inferred with a sensible choice.

[type.impl-trait]

# Impl trait

[type.impl-trait.syntax]

Syntax
ImplTraitType → impl TypeParamBounds

ImplTraitTypeOneBound → impl TraitBound

[type.impl-trait.intro]

`impl Trait` provides ways to specify unnamed but concrete types that implement a specific trait. It can appear in two sorts of places: argument position (where it can act as an anonymous type parameter to functions), and return position (where it can act as an abstract return type).

    #![allow(unused)]
    fn main() {
    trait Trait {}
    impl Trait for () {}

    // argument position: anonymous type parameter
    fn foo(arg: impl Trait) {
    }

    // return position: abstract return type
    fn bar() -> impl Trait {
    }
    }

[type.impl-trait.param]

## Anonymous type parameters

> Note

> This is often called “impl Trait in argument position”. (The term “parameter” is more correct here, but “impl Trait in argument position” is the phrasing used during the development of this feature, and it remains in parts of the implementation.)

[type.impl-trait.param.intro]

Functions can use `impl` followed by a set of trait bounds to declare a parameter as having an anonymous type. The caller must provide a type that satisfies the bounds declared by the anonymous type parameter, and the function can only use the methods available through the trait bounds of the anonymous type parameter.

For example, these two forms are almost equivalent:

    #![allow(unused)]
    fn main() {
    trait Trait {}

    // generic type parameter
    fn with_generic_type<T: Trait>(arg: T) {
    }

    // impl Trait in argument position
    fn with_impl_trait(arg: impl Trait) {
    }
    }

[type.impl-trait.param.generic]

That is, `impl Trait` in argument position is syntactic sugar for a generic type parameter like `<T: Trait>`, except that the type is anonymous and doesn’t appear in the GenericParams list.

> Note

> For function parameters, generic type parameters and `impl Trait` are not exactly equivalent. With a generic parameter such as `<T: Trait>`, the caller has the option to explicitly specify the generic argument for `T` at the call site using GenericArgs, for example, `foo::<usize>(1)`. Changing a parameter from either one to the other can constitute a breaking change for the callers of a function, since this changes the number of generic arguments.

[type.impl-trait.return]

## Abstract return types

> Note

> This is often called “impl Trait in return position”.

[type.impl-trait.return.intro]

Functions can use `impl Trait` to return an abstract return type. These types stand in for another concrete type where the caller may only use the methods declared by the specified `Trait`.

[type.impl-trait.return.constraint-body]

Each possible return value from the function must resolve to the same concrete type.

`impl Trait` in return position allows a function to return an unboxed abstract type. This is particularly useful with closures and iterators. For example, closures have a unique, un-writable type. Previously, the only way to return a closure from a function was to use a trait object:

    #![allow(unused)]
    fn main() {
    fn returns_closure() -> Box<dyn Fn(i32) -> i32> {
        Box::new(|x| x + 1)
    }
    }

This could incur performance penalties from heap allocation and dynamic dispatch. It wasn’t possible to fully specify the type of the closure, only to use the `Fn` trait. That means that the trait object is necessary. However, with `impl Trait`, it is possible to write this more simply:

    #![allow(unused)]
    fn main() {
    fn returns_closure() -> impl Fn(i32) -> i32 {
        |x| x + 1
    }
    }

which also avoids the drawbacks of using a boxed trait object.

Similarly, the concrete types of iterators could become very complex, incorporating the types of all previous iterators in a chain. Returning `impl Iterator` means that a function only exposes the `Iterator` trait as a bound on its return type, instead of explicitly specifying all of the other iterator types involved.

[type.impl-trait.return-in-trait]

## Return-position `impl Trait` in traits and trait implementations

[type.impl-trait.return-in-trait.intro]

Functions in traits may also use `impl Trait` as a syntax for an anonymous associated type.

[type.impl-trait.return-in-trait.desugaring]

Every `impl Trait` in the return type of an associated function in a trait is desugared to an anonymous associated type. The return type that appears in the implementation’s function signature is used to determine the value of the associated type.

[type.impl-trait.generic-captures]

## Capturing

Behind each return-position `impl Trait` abstract type is some hidden concrete type. For this concrete type to use a generic parameter, that generic parameter must be captured by the abstract type.

[type.impl-trait.generic-capture.auto]

## Automatic capturing

[type.impl-trait.generic-capture.auto.intro]

Return-position `impl Trait` abstract types automatically capture all in-scope generic parameters, including generic type, const, and lifetime parameters (including higher-ranked ones).

[type.impl-trait.generic-capture.edition2024]

> 2024 Edition differences

> Before the 2024 edition, on free functions and on associated functions and methods of inherent impls, generic lifetime parameters that do not appear in the bounds of the abstract return type are not automatically captured.

[type.impl-trait.generic-capture.precise]

## Precise capturing

[type.impl-trait.generic-capture.precise.use]

The set of generic parameters captured by a return-position `impl Trait` abstract type may be explicitly controlled with a `use<..>` bound. If present, only the generic parameters listed in the `use<..>` bound will be captured. E.g.:

    #![allow(unused)]
    fn main() {
    fn capture<'a, 'b, T>(x: &'a (), y: T) -> impl Sized + use<'a, T> {
      //                                      ~~~~~~~~~~~~~~~~~~~~~~~
      //                                     Captures `'a` and `T` only.
      (x, y)
    }
    }

[type.impl-trait.generic-capture.precise.constraint-single]

Currently, only one `use<..>` bound may be present in a bounds list, all in-scope type and const generic parameters must be included, and all lifetime parameters that appear in other bounds of the abstract type must be included.

[type.impl-trait.generic-capture.precise.constraint-lifetime]

Within the `use<..>` bound, any lifetime parameters present must appear before all type and const generic parameters, and the elided lifetime (`'_`) may be present if it is otherwise allowed to appear within the `impl Trait` return type.

[type.impl-trait.generic-capture.precise.constraint-param-impl-trait]

Because all in-scope type parameters must be included by name, a `use<..>` bound may not be used in the signature of items that use argument-position `impl Trait`, as those items have anonymous type parameters in scope.

[type.impl-trait.generic-capture.precise.constraint-in-trait]

Any `use<..>` bound that is present in an associated function in a trait definition must include all generic parameters of the trait, including the implicit `Self` generic type parameter of the trait.

## Differences between generics and `impl Trait` in return position

In argument position, `impl Trait` is very similar in semantics to a generic type parameter. However, there are significant differences between the two in return position. With `impl Trait`, unlike with a generic type parameter, the function chooses the return type, and the caller cannot choose the return type.

The function:

    #![allow(unused)]
    fn main() {
    trait Trait {}
    fn foo<T: Trait>() -> T {
        // ...
    panic!()
    }
    }

allows the caller to determine the return type, `T`, and the function returns that type.

The function:

    #![allow(unused)]
    fn main() {
    trait Trait {}
    impl Trait for () {}
    fn foo() -> impl Trait {
        // ...
    }
    }

doesn’t allow the caller to determine the return type. Instead, the function chooses the return type, but only promises that it will implement `Trait`.

[type.impl-trait.constraint]

## Limitations

`impl Trait` can only appear as a parameter or return type of a non-`extern` function. It cannot be the type of a `let` binding, field type, or appear inside a type alias.

[type.generic]

# Type parameters

Within the body of an item that has type parameter declarations, the names of its type parameters are types:

    #![allow(unused)]
    fn main() {
    fn to_vec<A: Clone>(xs: &[A]) -> Vec<A> {
        if xs.is_empty() {
            return vec![];
        }
        let first: A = xs[0].clone();
        let mut rest: Vec<A> = to_vec(&xs[1..]);
        rest.insert(0, first);
        rest
    }
    }

Here, `first` has type `A`, referring to `to_vec`’s `A` type parameter; and `rest` has type `Vec<A>`, a vector with element type `A`.

[type.inferred]

# Inferred type

[type.inferred.syntax]

Syntax
InferredType → _

[type.inferred.intro]

The inferred type asks the compiler to infer the type if possible based on the surrounding information available.

> Example

> The inferred type is often used in generic arguments:

>     #![allow(unused)]
>     fn main() {
>     let x: Vec<_> = (0..10).collect();
>     }

[type.inferred.constraint]

The inferred type cannot be used in item signatures.

[dynamic-sized]

# Dynamically sized types

[dynamic-sized.intro]

Most types have a fixed size that is known at compile time and implement the trait `Sized`. A type with a size that is known only at run-time is called a dynamically sized type (DST) or, informally, an unsized type. Slices, trait objects, and str are examples of DSTs.

[dynamic-sized.restriction]

Such types can only be used in certain cases:

[dynamic-sized.pointer-types]

- Pointer types to DSTs are sized but have twice the size of pointers to sized types
  - Pointers to slices and `str` also store the number of elements.
  - Pointers to trait objects also store a pointer to a vtable.

[dynamic-sized.question-sized]

- DSTs can be provided as type arguments to generic type parameters having the special `?Sized` bound. They can also be used for associated type definitions when the corresponding associated type declaration has a `?Sized` bound. By default, any type parameter or associated type has a `Sized` bound, unless it is relaxed using `?Sized`.

[dynamic-sized.trait-impl]

- Traits may be implemented for DSTs. Unlike with generic type parameters, `Self: ?Sized` is the default in trait definitions.

[dynamic-sized.struct-field]

- Structs may contain a DST as the last field; this makes the struct itself a DST.

> Note

> Variables, function parameters, const items, and static items must be `Sized`.

[layout]

# Type layout

[layout.intro]

The layout of a type is its size, alignment, and the relative offsets of its fields. For enums, how the discriminant is laid out and interpreted is also part of type layout.

[layout.guarantees]

Type layout can be changed with each compilation. Instead of trying to document exactly what is done, we only document what is guaranteed today.

Note that even types with the same layout can still differ in how they are passed across function boundaries. For function call ABI compatibility of types, see here.

[layout.properties]

## Size and alignment

All values have an alignment and size.

[layout.properties.align]

The alignment of a value specifies what addresses are valid to store the value at. A value of alignment `n` must only be stored at an address that is a multiple of n. For example, a value with an alignment of 2 must be stored at an even address, while a value with an alignment of 1 can be stored at any address. Alignment is measured in bytes, and must be at least 1, and always a power of 2. The alignment of a value can be checked with the `align_of_val` function.

[layout.properties.size]

The size of a value is the offset in bytes between successive elements in an array with that item type including alignment padding. The size of a value is always a multiple of its alignment. Note that some types are zero-sized; 0 is considered a multiple of any alignment (for example, on some platforms, the type `[u16; 0]` has size 0 and alignment 2). The size of a value can be checked with the `size_of_val` function.

[layout.properties.sized]

Types where all values have the same size and alignment, and both are known at compile time, implement the `Sized` trait and can be checked with the `size_of` and `align_of` functions. Types that are not `Sized` are known as dynamically sized types. Since all values of a `Sized` type share the same size and alignment, we refer to those shared values as the size of the type and the alignment of the type respectively.

[layout.primitive]

## Primitive data layout

[layout.primitive.size]

The size of most primitives is given in this table.

Type | `size_of::<Type>()`
--- | ---
`bool` | 1
`u8` / `i8` | 1
`u16` / `i16` | 2
`u32` / `i32` | 4
`u64` / `i64` | 8
`u128` / `i128` | 16
`usize` / `isize` | See below
`f32` | 4
`f64` | 8
`char` | 4

[layout.primitive.size-int]

`usize` and `isize` have a size big enough to contain every address on the target platform. For example, on a 32 bit target, this is 4 bytes, and on a 64 bit target, this is 8 bytes.

[layout.primitive.align]

The alignment of primitives is platform-specific. In most cases, their alignment is equal to their size, but it may be less. In particular, `i128` and `u128` are often aligned to 4 or 8 bytes even though their size is 16, and on many 32-bit platforms, `i64`, `u64`, and `f64` are only aligned to 4 bytes, not 8.

[layout.pointer]

## Pointers and references layout

[layout.pointer.intro]

Pointers and references have the same layout. Mutability of the pointer or reference does not change the layout.

[layout.pointer.thin]

Pointers to sized types have the same size and alignment as `usize`.

[layout.pointer.unsized]

Pointers to unsized types are sized. The size and alignment is guaranteed to be at least equal to the size and alignment of a pointer.

> Note

> Though you should not rely on this, all pointers to DSTs are currently twice the size of the size of `usize` and have the same alignment.

[layout.array]

## Array layout

An array of `[T; N]` has a size of `size_of::<T>() * N` and the same alignment of `T`. Arrays are laid out so that the zero-based `nth` element of the array is offset from the start of the array by `n * size_of::<T>()` bytes.

[layout.slice]

## Slice layout

Slices have the same layout as the section of the array they slice.

> Note

> This is about the raw `[T]` type, not pointers (`&[T]`, `Box<[T]>`, etc.) to slices.

[layout.str]

## `str` Layout

String slices are a UTF-8 representation of characters that have the same layout as slices of type `[u8]`. A reference `&str` has the same layout as a reference `&[u8]`.

[layout.tuple]

## Tuple layout

[layout.tuple.general]

Tuples are laid out according to the `Rust` representation.

[layout.tuple.unit]

The exception to this is the unit tuple (`()`), which is guaranteed as a zero-sized type to have a size of 0 and an alignment of 1.

[layout.trait-object]

## Trait object layout

Trait objects have the same layout as the value the trait object is of.

> Note

> This is about the raw trait object types, not pointers (`&dyn Trait`, `Box<dyn Trait>`, etc.) to trait objects.

[layout.closure]

## Closure layout

Closures have no layout guarantees.

[layout.repr]

## Representations

[layout.repr.intro]

All user-defined composite types (`struct`s, `enum`s, and `union`s) have a representation that specifies what the layout is for the type.

[layout.repr.kinds]

The possible representations for a type are:

- `Rust` (default)
- `C`
- The primitive representations
- `transparent`

[layout.repr.attribute]

The representation of a type can be changed by applying the `repr` attribute to it. The following example shows a struct with a `C` representation.

    #![allow(unused)]
    fn main() {
    #[repr(C)]
    struct ThreeInts {
        first: i16,
        second: i8,
        third: i32
    }
    }

[layout.repr.align-packed]

The alignment may be raised or lowered with the `align` and `packed` modifiers respectively. They alter the representation specified in the attribute. If no representation is specified, the default one is altered.

    #![allow(unused)]
    fn main() {
    // Default representation, alignment lowered to 2.
    #[repr(packed(2))]
    struct PackedStruct {
        first: i16,
        second: i8,
        third: i32
    }

    // C representation, alignment raised to 8
    #[repr(C, align(8))]
    struct AlignedStruct {
        first: i16,
        second: i8,
        third: i32
    }
    }

> Note

> As a consequence of the representation being an attribute on the item, the representation does not depend on generic parameters. Any two types with the same name have the same representation. For example, `Foo<Bar>` and `Foo<Baz>` both have the same representation.

[layout.repr.inter-field]

The representation of a type can change the padding between fields, but does not change the layout of the fields themselves. For example, a struct with a `C` representation that contains a struct `Inner` with the `Rust` representation will not change the layout of `Inner`.

[layout.repr.rust]

### The `Rust` representation

[layout.repr.rust.intro]

The `Rust` representation is the default representation for nominal types without a `repr` attribute. Using this representation explicitly through a `repr` attribute is guaranteed to be the same as omitting the attribute entirely.

[layout.repr.rust.layout]

The only data layout guarantees made by this representation are those required for soundness. They are:

1. The fields are properly aligned.
2. The fields do not overlap.
3. The alignment of the type is at least the maximum alignment of its fields.

[layout.repr.rust.alignment]

Formally, the first guarantee means that the offset of any field is divisible by that field’s alignment.

[layout.repr.rust.field-storage]

The second guarantee means that the fields can be ordered such that the offset plus the size of any field is less than or equal to the offset of the next field in the ordering. The ordering does not have to be the same as the order in which the fields are specified in the declaration of the type.

Be aware that the second guarantee does not imply that the fields have distinct addresses: zero-sized types may have the same address as other fields in the same struct.

[layout.repr.rust.unspecified]

There are no other guarantees of data layout made by this representation.

[layout.repr.c]

### The `C` representation

[layout.repr.c.intro]

The `C` representation is designed for dual purposes. One purpose is for creating types that are interoperable with the C Language. The second purpose is to create types that you can soundly perform operations on that rely on data layout such as reinterpreting values as a different type.

Because of this dual purpose, it is possible to create types that are not useful for interfacing with the C programming language.

[layout.repr.c.constraint]

This representation can be applied to structs, unions, and enums. The exception is zero-variant enums for which the `C` representation is an error.

[layout.repr.c.struct]

#### `#[repr(C)]` Structs

[layout.repr.c.struct.align]

The alignment of the struct is the alignment of the most-aligned field in it.

[layout.repr.c.struct.size-field-offset]

The size and offset of fields is determined by the following algorithm.

Start with a current offset of 0 bytes.

For each field in declaration order in the struct, first determine the size and alignment of the field. If the current offset is not a multiple of the field’s alignment, then add padding bytes to the current offset until it is a multiple of the field’s alignment. The offset for the field is what the current offset is now. Then increase the current offset by the size of the field.

Finally, the size of the struct is the current offset rounded up to the nearest multiple of the struct’s alignment.

Here is this algorithm described in pseudocode.

    /// Returns the amount of padding needed after `offset` to ensure that the
    /// following address will be aligned to `alignment`.
    fn padding_needed_for(offset: usize, alignment: usize) -> usize {
        let misalignment = offset % alignment;
        if misalignment > 0 {
            // round up to next multiple of `alignment`
            alignment - misalignment
        } else {
            // already a multiple of `alignment`
            0
        }
    }

    struct.alignment = struct.fields().map(|field| field.alignment).max();

    let current_offset = 0;

    for field in struct.fields_in_declaration_order() {
        // Increase the current offset so that it's a multiple of the alignment
        // of this field. For the first field, this will always be zero.
        // The skipped bytes are called padding bytes.
        current_offset += padding_needed_for(current_offset, field.alignment);

        struct[field].offset = current_offset;

        current_offset += field.size;
    }

    struct.size = current_offset + padding_needed_for(current_offset, struct.alignment);

> Warning

> This pseudocode uses a naive algorithm that ignores overflow issues for the sake of clarity. To perform memory layout computations in actual code, use `Layout`.

> Note

> This algorithm can produce zero-sized structs. In C, an empty struct declaration like `struct Foo { }` is illegal. However, both gcc and clang support options to enable such structs, and assign them size zero. C++, in contrast, gives empty structs a size of 1, unless they are inherited from or they are fields that have the `[[no_unique_address]]` attribute, in which case they do not increase the overall size of the struct.

[layout.repr.c.union]

#### `#[repr(C)]` Unions

[layout.repr.c.union.intro]

A union declared with `#[repr(C)]` will have the same size and alignment as an equivalent C union declaration in the C language for the target platform.

[layout.repr.c.union.size-align]

The union will have a size of the maximum size of all of its fields rounded to its alignment, and an alignment of the maximum alignment of all of its fields. These maximums may come from different fields.

    #![allow(unused)]
    fn main() {
    #[repr(C)]
    union Union {
        f1: u16,
        f2: [u8; 4],
    }

    assert_eq!(std::mem::size_of::<Union>(), 4);  // From f2
    assert_eq!(std::mem::align_of::<Union>(), 2); // From f1

    #[repr(C)]
    union SizeRoundedUp {
       a: u32,
       b: [u16; 3],
    }

    assert_eq!(std::mem::size_of::<SizeRoundedUp>(), 8);  // Size of 6 from b,
                                                          // rounded up to 8 from
                                                          // alignment of a.
    assert_eq!(std::mem::align_of::<SizeRoundedUp>(), 4); // From a
    }

[layout.repr.c.enum]

#### `#[repr(C)]` Field-less Enums

For field-less enums, the `C` representation has the size and alignment of the default `enum` size and alignment for the target platform’s C ABI.

> Note

> The enum representation in C is implementation defined, so this is really a “best guess”. In particular, this may be incorrect when the C code of interest is compiled with certain flags.

> Warning

> There are crucial differences between an `enum` in the C language and Rust’s field-less enums with this representation. An `enum` in C is mostly a `typedef` plus some named constants; in other words, an object of an `enum` type can hold any integer value. For example, this is often used for bitflags in `C`. In contrast, Rust’s field-less enums can only legally hold the discriminant values, everything else is undefined behavior. Therefore, using a field-less enum in FFI to model a C `enum` is often wrong.

[layout.repr.c.adt]

#### `#[repr(C)]` Enums With Fields

[layout.repr.c.adt.intro]

The representation of a `repr(C)` enum with fields is a `repr(C)` struct with two fields, also called a “tagged union” in C:

[layout.repr.c.adt.tag]

- a `repr(C)` version of the enum with all fields removed (“the tag”)

[layout.repr.c.adt.fields]

- a `repr(C)` union of `repr(C)` structs for the fields of each variant that had them (“the payload”)

> Note

> Due to the representation of `repr(C)` structs and unions, if a variant has a single field there is no difference between putting that field directly in the union or wrapping it in a struct; any system which wishes to manipulate such an `enum`’s representation may therefore use whichever form is more convenient or consistent for them.

    #![allow(unused)]
    fn main() {
    // This Enum has the same representation as ...
    #[repr(C)]
    enum MyEnum {
        A(u32),
        B(f32, u64),
        C { x: u32, y: u8 },
        D,
     }

    // ... this struct.
    #[repr(C)]
    struct MyEnumRepr {
        tag: MyEnumDiscriminant,
        payload: MyEnumFields,
    }

    // This is the discriminant enum.
    #[repr(C)]
    enum MyEnumDiscriminant { A, B, C, D }

    // This is the variant union.
    #[repr(C)]
    union MyEnumFields {
        A: MyAFields,
        B: MyBFields,
        C: MyCFields,
        D: MyDFields,
    }

    #[repr(C)]
    #[derive(Copy, Clone)]
    struct MyAFields(u32);

    #[repr(C)]
    #[derive(Copy, Clone)]
    struct MyBFields(f32, u64);

    #[repr(C)]
    #[derive(Copy, Clone)]
    struct MyCFields { x: u32, y: u8 }

    // This struct could be omitted (it is a zero-sized type), and it must be in
    // C/C++ headers.
    #[repr(C)]
    #[derive(Copy, Clone)]
    struct MyDFields;
    }

[layout.repr.primitive]

### Primitive representations

[layout.repr.primitive.intro]

The primitive representations are the representations with the same names as the primitive integer types. That is: `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, and `isize`.

[layout.repr.primitive.constraint]

Primitive representations can only be applied to enumerations and have different behavior whether the enum has fields or no fields. It is an error for zero-variant enums to have a primitive representation. Combining two primitive representations together is an error.

[layout.repr.primitive.enum]

#### Primitive representation of field-less enums

For field-less enums, primitive representations set the size and alignment to be the same as the primitive type of the same name. For example, a field-less enum with a `u8` representation can only have discriminants between 0 and 255 inclusive.

[layout.repr.primitive.adt]

#### Primitive representation of enums with fields

The representation of a primitive representation enum is a `repr(C)` union of `repr(C)` structs for each variant with a field. The first field of each struct in the union is the primitive representation version of the enum with all fields removed (“the tag”) and the remaining fields are the fields of that variant.

> Note

> This representation is unchanged if the tag is given its own member in the union, should that make manipulation more clear for you (although to follow the C++ standard the tag member should be wrapped in a `struct`).

    #![allow(unused)]
    fn main() {
    // This enum has the same representation as ...
    #[repr(u8)]
    enum MyEnum {
        A(u32),
        B(f32, u64),
        C { x: u32, y: u8 },
        D,
     }

    // ... this union.
    #[repr(C)]
    union MyEnumRepr {
        A: MyVariantA,
        B: MyVariantB,
        C: MyVariantC,
        D: MyVariantD,
    }

    // This is the discriminant enum.
    #[repr(u8)]
    #[derive(Copy, Clone)]
    enum MyEnumDiscriminant { A, B, C, D }

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct MyVariantA(MyEnumDiscriminant, u32);

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct MyVariantB(MyEnumDiscriminant, f32, u64);

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct MyVariantC { tag: MyEnumDiscriminant, x: u32, y: u8 }

    #[repr(C)]
    #[derive(Clone, Copy)]
    struct MyVariantD(MyEnumDiscriminant);
    }

[layout.repr.primitive-c]

#### Combining primitive representations of enums with fields and `#[repr(C)]`

For enums with fields, it is also possible to combine `repr(C)` and a primitive representation (e.g., `repr(C, u8)`). This modifies the `repr(C)` by changing the representation of the discriminant enum to the chosen primitive instead. So, if you chose the `u8` representation, then the discriminant enum would have a size and alignment of 1 byte.

The discriminant enum from the example earlier then becomes:

    #![allow(unused)]
    fn main() {
    #[repr(C, u8)] // `u8` was added
    enum MyEnum {
        A(u32),
        B(f32, u64),
        C { x: u32, y: u8 },
        D,
     }

    // ...

    #[repr(u8)] // So `u8` is used here instead of `C`
    enum MyEnumDiscriminant { A, B, C, D }

    // ...
    }

For example, with a `repr(C, u8)` enum it is not possible to have 257 unique discriminants (“tags”) whereas the same enum with only a `repr(C)` attribute will compile without any problems.

Using a primitive representation in addition to `repr(C)` can change the size of an enum from the `repr(C)` form:

    #![allow(unused)]
    fn main() {
    #[repr(C)]
    enum EnumC {
        Variant0(u8),
        Variant1,
    }

    #[repr(C, u8)]
    enum Enum8 {
        Variant0(u8),
        Variant1,
    }

    #[repr(C, u16)]
    enum Enum16 {
        Variant0(u8),
        Variant1,
    }

    // The size of the C representation is platform dependent
    assert_eq!(std::mem::size_of::<EnumC>(), 8);
    // One byte for the discriminant and one byte for the value in Enum8::Variant0
    assert_eq!(std::mem::size_of::<Enum8>(), 2);
    // Two bytes for the discriminant and one byte for the value in Enum16::Variant0
    // plus one byte of padding.
    assert_eq!(std::mem::size_of::<Enum16>(), 4);
    }

[layout.repr.alignment]

### The alignment modifiers

[layout.repr.alignment.intro]

The `align` and `packed` modifiers can be used to respectively raise or lower the alignment of `struct`s and `union`s. `packed` may also alter the padding between fields (although it will not alter the padding inside of any field). On their own, `align` and `packed` do not provide guarantees about the order of fields in the layout of a struct or the layout of an enum variant, although they may be combined with representations (such as `C`) which do provide such guarantees.

[layout.repr.alignment.constraint-alignment]

The alignment is specified as an integer parameter in the form of `#[repr(align(x))]` or `#[repr(packed(x))]`. The alignment value must be a power of two from 1 up to 229. For `packed`, if no value is given, as in `#[repr(packed)]`, then the value is 1.

[layout.repr.alignment.align]

For `align`, if the specified alignment is less than the alignment of the type without the `align` modifier, then the alignment is unaffected.

[layout.repr.alignment.packed]

For `packed`, if the specified alignment is greater than the type’s alignment without the `packed` modifier, then the alignment and layout is unaffected.

[layout.repr.alignment.packed-fields]

The alignments of each field, for the purpose of positioning fields, is the smaller of the specified alignment and the alignment of the field’s type.

[layout.repr.alignment.packed-padding]

Inter-field padding is guaranteed to be the minimum required in order to satisfy each field’s (possibly altered) alignment (although note that, on its own, `packed` does not provide any guarantee about field ordering). An important consequence of these rules is that a type with `#[repr(packed(1))]` (or `#[repr(packed)]`) will have no inter-field padding.

[layout.repr.alignment.constraint-exclusive]

The `align` and `packed` modifiers cannot be applied on the same type and a `packed` type cannot transitively contain another `align`ed type. `align` and `packed` may only be applied to the `Rust` and `C` representations.

[layout.repr.alignment.enum]

The `align` modifier can also be applied on an `enum`. When it is, the effect on the `enum`’s alignment is the same as if the `enum` was wrapped in a newtype `struct` with the same `align` modifier.

> Note

> References to unaligned fields are not allowed because it is undefined behavior. When fields are unaligned due to an alignment modifier, consider the following options for using references and dereferences:

>     #![allow(unused)]
>     fn main() {
>     #[repr(packed)]
>     struct Packed {
>         f1: u8,
>         f2: u16,
>     }
>     let mut e = Packed { f1: 1, f2: 2 };
>     // Instead of creating a reference to a field, copy the value to a local variable.
>     let x = e.f2;
>     // Or in situations like `println!` which creates a reference, use braces
>     // to change it to a copy of the value.
>     println!("{}", {e.f2});
>     // Or if you need a pointer, use the unaligned methods for reading and writing
>     // instead of dereferencing the pointer directly.
>     let ptr: *const u16 = &raw const e.f2;
>     let value = unsafe { ptr.read_unaligned() };
>     let mut_ptr: *mut u16 = &raw mut e.f2;
>     unsafe { mut_ptr.write_unaligned(3) }
>     }

[layout.repr.transparent]

### The `transparent` representation

[layout.repr.transparent.constraint-field]

The `transparent` representation can only be used on a `struct` or an `enum` with a single variant that has:

- any number of fields with size 0 and alignment 1 (e.g. `PhantomData<T>`), and
- at most one other field.

[layout.repr.transparent.layout-abi]

Structs and enums with this representation have the same layout and ABI as the only non-size 0 non-alignment 1 field, if present, or unit otherwise.

This is different than the `C` representation because a struct with the `C` representation will always have the ABI of a `C` `struct` while, for example, a struct with the `transparent` representation with a primitive field will have the ABI of the primitive field.

[layout.repr.transparent.constraint-exclusive]

Because this representation delegates type layout to another type, it cannot be used with any other representation.

[interior-mut]

# Interior mutability

[interior-mut.intro]

Sometimes a type needs to be mutated while having multiple aliases. In Rust this is achieved using a pattern called interior mutability.

[interior-mut.shared-ref]

A type has interior mutability if its internal state can be changed through a shared reference to it.

[interior-mut.no-constraint]

This goes against the usual requirement that the value pointed to by a shared reference is not mutated.

[interior-mut.unsafe-cell]

`std::cell::UnsafeCell<T>` type is the only allowed way to disable this requirement. When `UnsafeCell<T>` is immutably aliased, it is still safe to mutate, or obtain a mutable reference to, the `T` it contains.

[interior-mut.mut-unsafe-cell]

As with all other types, it is undefined behavior to have multiple `&mut UnsafeCell<T>` aliases.

[interior-mut.abstraction]

Other types with interior mutability can be created by using `UnsafeCell<T>` as a field. The standard library provides a variety of types that provide safe interior mutability APIs.

[interior-mut.ref-cell]

For example, `std::cell::RefCell<T>` uses run-time borrow checks to ensure the usual rules around multiple references.

[interior-mut.atomic]

The `std::sync::atomic` module contains types that wrap a value that is only accessed with atomic operations, allowing the value to be shared and mutated across threads.

[subtype]

# Subtyping and variance

[subtype.intro]

Subtyping is implicit and can occur at any stage in type checking or inference.

[subtype.kinds]

Subtyping is restricted to two cases: variance with respect to lifetimes and between types with higher ranked lifetimes. If we were to erase lifetimes from types, then the only subtyping would be due to type equality.

Consider the following example: string literals always have `'static` lifetime. Nevertheless, we can assign `s` to `t`:

    #![allow(unused)]
    fn main() {
    fn bar<'a>() {
        let s: &'static str = "hi";
        let t: &'a str = s;
    }
    }

Since `'static` outlives the lifetime parameter `'a`, `&'static str` is a subtype of `&'a str`.

[subtype.higher-ranked]

Higher-ranked function pointers and trait objects have another subtype relation. They are subtypes of types that are given by substitutions of the higher-ranked lifetimes. Some examples:

    #![allow(unused)]
    fn main() {
    // Here 'a is substituted for 'static
    let subtype: &(for<'a> fn(&'a i32) -> &'a i32) = &((|x| x) as fn(&_) -> &_);
    let supertype: &(fn(&'static i32) -> &'static i32) = subtype;

    // This works similarly for trait objects
    let subtype: &(dyn for<'a> Fn(&'a i32) -> &'a i32) = &|x| x;
    let supertype: &(dyn Fn(&'static i32) -> &'static i32) = subtype;

    // We can also substitute one higher-ranked lifetime for another
    let subtype: &(for<'a, 'b> fn(&'a i32, &'b i32)) = &((|x, y| {}) as fn(&_, &_));
    let supertype: &for<'c> fn(&'c i32, &'c i32) = subtype;
    }

[subtyping.variance]

## Variance

[subtyping.variance.intro]

Variance is a property that generic types have with respect to their arguments. A generic type’s variance in a parameter is how the subtyping of the parameter affects the subtyping of the type.

[subtyping.variance.covariant]

- `F<T>` is covariant over `T` if `T` being a subtype of `U` implies that `F<T>` is a subtype of `F<U>` (subtyping “passes through”)

[subtyping.variance.contravariant]

- `F<T>` is contravariant over `T` if `T` being a subtype of `U` implies that `F<U>` is a subtype of `F<T>`

[subtyping.variance.invariant]

- `F<T>` is invariant over `T` otherwise (no subtyping relation can be derived)

[subtyping.variance.builtin-types]

Variance of types is automatically determined as follows

Type | Variance in `'a` | Variance in `T`
--- | --- | ---
`&'a T` | covariant | covariant
`&'a mut T` | covariant | invariant
`*const T` |  | covariant
`*mut T` |  | invariant
`[T]` and `[T; n]` |  | covariant
`fn() -> T` |  | covariant
`fn(T) -> ()` |  | contravariant
`std::cell::UnsafeCell<T>` |  | invariant
`std::marker::PhantomData<T>` |  | covariant
`dyn Trait<T> + 'a` | covariant | invariant

[subtyping.variance.user-composite-types]

The variance of other `struct`, `enum`, and `union` types is decided by looking at the variance of the types of their fields. If the parameter is used in positions with different variances then the parameter is invariant. For example the following struct is covariant in `'a` and `T` and invariant in `'b`, `'c`, and `U`.

    #![allow(unused)]
    fn main() {
    use std::cell::UnsafeCell;
    struct Variance<'a, 'b, 'c, T, U: 'a> {
        x: &'a U,               // This makes `Variance` covariant in 'a, and would
                                // make it covariant in U, but U is used later
        y: *const T,            // Covariant in T
        z: UnsafeCell<&'b f64>, // Invariant in 'b
        w: *mut U,              // Invariant in U, makes the whole struct invariant

        f: fn(&'c ()) -> &'c () // Both co- and contravariant, makes 'c invariant
                                // in the struct.
    }
    }

[subtyping.variance.builtin-composite-types]

When used outside of an `struct`, `enum`, or `union`, the variance for parameters is checked at each location separately.

    #![allow(unused)]
    fn main() {
    use std::cell::UnsafeCell;
    fn generic_tuple<'short, 'long: 'short>(
        // 'long is used inside of a tuple in both a co- and invariant position.
        x: (&'long u32, UnsafeCell<&'long u32>),
    ) {
        // As the variance at these positions is computed separately,
        // we can freely shrink 'long in the covariant position.
        let _: (&'short u32, UnsafeCell<&'long u32>) = x;
    }

    fn takes_fn_ptr<'short, 'middle: 'short>(
        // 'middle is used in both a co- and contravariant position.
        f: fn(&'middle ()) -> &'middle (),
    ) {
        // As the variance at these positions is computed separately,
        // we can freely shrink 'middle in the covariant position
        // and extend it in the contravariant position.
        let _: fn(&'static ()) -> &'short () = f;
    }
    }

[bound]

# Trait and lifetime bounds

[bound.syntax]

Syntax
TypeParamBounds → TypeParamBound ( + TypeParamBound )* +?

TypeParamBound → Lifetime | TraitBound | UseBound

TraitBound →
( ? | ForLifetimes )? TypePath
| ( ( ? | ForLifetimes )? TypePath )

LifetimeBounds → ( Lifetime + )* Lifetime?

Lifetime →
LIFETIME_OR_LABEL
| 'static
| '_

UseBound → use UseBoundGenericArgs

UseBoundGenericArgs →
< >
| < ( UseBoundGenericArg , )* UseBoundGenericArg ,? >

UseBoundGenericArg →
Lifetime
| IDENTIFIER
| Self

[bound.intro]

Trait and lifetime bounds provide a way for generic items to restrict which types and lifetimes are used as their parameters. Bounds can be provided on any type in a where clause. There are also shorter forms for certain common cases:

- Bounds written after declaring a generic parameter: `fn f<A: Copy>() {}` is the same as `fn f<A>() where A: Copy {}`.
- In trait declarations as supertraits: `trait Circle : Shape {}` is equivalent to `trait Circle where Self : Shape {}`.
- In trait declarations as bounds on associated types: `trait A { type B: Copy; }` is equivalent to `trait A where Self::B: Copy { type B; }`.

[bound.satisfaction]

Bounds on an item must be satisfied when using the item. When type checking and borrow checking a generic item, the bounds can be used to determine that a trait is implemented for a type. For example, given `Ty: Trait`

- In the body of a generic function, methods from `Trait` can be called on `Ty` values. Likewise associated constants on the `Trait` can be used.
- Associated types from `Trait` can be used.
- Generic functions and types with a `T: Trait` bounds can be used with `Ty` being used for `T`.

    #![allow(unused)]
    fn main() {
    type Surface = i32;
    trait Shape {
        fn draw(&self, surface: Surface);
        fn name() -> &'static str;
    }

    fn draw_twice<T: Shape>(surface: Surface, sh: T) {
        sh.draw(surface);           // Can call method because T: Shape
        sh.draw(surface);
    }

    fn copy_and_draw_twice<T: Copy>(surface: Surface, sh: T) where T: Shape {
        let shape_copy = sh;        // doesn't move sh because T: Copy
        draw_twice(surface, sh);    // Can use generic function because T: Shape
    }

    struct Figure<S: Shape>(S, S);

    fn name_figure<U: Shape>(
        figure: Figure<U>,          // Type Figure<U> is well-formed because U: Shape
    ) {
        println!(
            "Figure of two {}",
            U::name(),              // Can use associated function
        );
    }
    }

[bound.trivial]

Bounds that don’t use the item’s parameters or higher-ranked lifetimes are checked when the item is defined. It is an error for such a bound to be false.

[bound.special]

`Copy`, `Clone`, and `Sized` bounds are also checked for certain generic types when using the item, even if the use does not provide a concrete type. It is an error to have `Copy` or `Clone` as a bound on a mutable reference, trait object, or slice. It is an error to have `Sized` as a bound on a trait object or slice.

    #![allow(unused)]
    fn main() {
    struct A<'a, T>
    where
        i32: Default,           // Allowed, but not useful
        i32: Iterator,          // Error: `i32` is not an iterator
        &'a mut T: Copy,        // (at use) Error: the trait bound is not satisfied
        [T]: Sized,             // (at use) Error: size cannot be known at compilation
    {
        f: &'a T,
    }
    struct UsesA<'a, T>(A<'a, T>);
    }

[bound.trait-object]

Trait and lifetime bounds are also used to name trait objects.

[bound.sized]

## `?Sized`

`?` is only used to relax the implicit `Sized` trait bound for type parameters or associated types. `?Sized` may not be used as a bound for other types.

[bound.lifetime]

## Lifetime bounds

[bound.lifetime.intro]

Lifetime bounds can be applied to types or to other lifetimes.

[bound.lifetime.outlive-lifetime]

The bound `'a: 'b` is usually read as `'a` outlives `'b`. `'a: 'b` means that `'a` lasts at least as long as `'b`, so a reference `&'a ()` is valid whenever `&'b ()` is valid.

    #![allow(unused)]
    fn main() {
    fn f<'a, 'b>(x: &'a i32, mut y: &'b i32) where 'a: 'b {
        y = x;                      // &'a i32 is a subtype of &'b i32 because 'a: 'b
        let r: &'b &'a i32 = &&0;   // &'b &'a i32 is well formed because 'a: 'b
    }
    }

[bound.lifetime.outlive-type]

`T: 'a` means that all lifetime parameters of `T` outlive `'a`. For example, if `'a` is an unconstrained lifetime parameter, then `i32: 'static` and `&'static str: 'a` are satisfied, but `Vec<&'a ()>: 'static` is not.

[bound.higher-ranked]

## Higher-ranked trait bounds

[bound.higher-ranked.syntax]

Syntax
ForLifetimes → for GenericParams

[bound.higher-ranked.intro]

Trait bounds may be higher ranked over lifetimes. These bounds specify a bound that is true for all lifetimes. For example, a bound such as `for<'a> &'a T: PartialEq<i32>` would require an implementation like

    #![allow(unused)]
    fn main() {
    struct T;
    impl<'a> PartialEq<i32> for &'a T {
        // ...
       fn eq(&self, other: &i32) -> bool {true}
    }
    }

and could then be used to compare a `&'a T` with any lifetime to an `i32`.

Only a higher-ranked bound can be used here, because the lifetime of the reference is shorter than any possible lifetime parameter on the function:

    #![allow(unused)]
    fn main() {
    fn call_on_ref_zero<F>(f: F) where for<'a> F: Fn(&'a i32) {
        let zero = 0;
        f(&zero);
    }
    }

[bound.higher-ranked.trait]

Higher-ranked lifetimes may also be specified just before the trait: the only difference is the scope of the lifetime parameter, which extends only to the end of the following trait instead of the whole bound. This function is equivalent to the last one.

    #![allow(unused)]
    fn main() {
    fn call_on_ref_zero<F>(f: F) where F: for<'a> Fn(&'a i32) {
        let zero = 0;
        f(&zero);
    }
    }

[bound.implied]

## Implied bounds

[bound.implied.intro]

Lifetime bounds required for types to be well-formed are sometimes inferred.

    #![allow(unused)]
    fn main() {
    fn requires_t_outlives_a<'a, T>(x: &'a T) {}
    }

The type parameter `T` is required to outlive `'a` for the type `&'a T` to be well-formed. This is inferred because the function signature contains the type `&'a T` which is only valid if `T: 'a` holds.

[bound.implied.context]

Implied bounds are added for all parameters and outputs of functions. Inside of `requires_t_outlives_a` you can assume `T: 'a` to hold even if you don’t explicitly specify this:

    #![allow(unused)]
    fn main() {
    fn requires_t_outlives_a_not_implied<'a, T: 'a>() {}

    fn requires_t_outlives_a<'a, T>(x: &'a T) {
        // This compiles, because `T: 'a` is implied by
        // the reference type `&'a T`.
        requires_t_outlives_a_not_implied::<'a, T>();
    }
    }

    #![allow(unused)]
    fn main() {
    fn requires_t_outlives_a_not_implied<'a, T: 'a>() {}
    fn not_implied<'a, T>() {
        // This errors, because `T: 'a` is not implied by
        // the function signature.
        requires_t_outlives_a_not_implied::<'a, T>();
    }
    }

[bound.implied.trait]

Only lifetime bounds are implied, trait bounds still have to be explicitly added. The following example therefore causes an error:

    #![allow(unused)]
    fn main() {
    use std::fmt::Debug;
    struct IsDebug<T: Debug>(T);
    // error[E0277]: `T` doesn't implement `Debug`
    fn doesnt_specify_t_debug<T>(x: IsDebug<T>) {}
    }

[bound.implied.def]

Lifetime bounds are also inferred for type definitions and impl blocks for any type:

    #![allow(unused)]
    fn main() {
    struct Struct<'a, T> {
        // This requires `T: 'a` to be well-formed
        // which is inferred by the compiler.
        field: &'a T,
    }

    enum Enum<'a, T> {
        // This requires `T: 'a` to be well-formed,
        // which is inferred by the compiler.
        //
        // Note that `T: 'a` is required even when only
        // using `Enum::OtherVariant`.
        SomeVariant(&'a T),
        OtherVariant,
    }

    trait Trait<'a, T: 'a> {}

    // This would error because `T: 'a` is not implied by any type
    // in the impl header.
    //     impl<'a, T> Trait<'a, T> for () {}

    // This compiles as `T: 'a` is implied by the self type `&'a T`.
    impl<'a, T> Trait<'a, T> for &'a T {}
    }

[bound.use]

## Use bounds

Certain bounds lists may include a `use<..>` bound to control which generic parameters are captured by the `impl Trait` abstract return type. See precise capturing for more details.

[coerce]

# Type coercions

[coerce.intro]

Type coercions are implicit operations that change the type of a value. They happen automatically at specific locations and are highly restricted in what types actually coerce.

[coerce.as]

Any conversions allowed by coercion can also be explicitly performed by the type cast operator, `as`.

Coercions are originally defined in RFC 401 and expanded upon in RFC 1558.

[coerce.site]

## Coercion sites

[coerce.site.intro]

A coercion can only occur at certain coercion sites in a program; these are typically places where the desired type is explicit or can be derived by propagation from explicit types (without type inference). Possible coercion sites are:

[coerce.site.let]

- `let` statements where an explicit type is given.

  For example, `&mut 42` is coerced to have type `&i8` in the following:

      #![allow(unused)]
      fn main() {
      let _: &i8 = &mut 42;
      }

[coerce.site.value]

- `static` and `const` item declarations (similar to `let` statements).

[coerce.site.argument]

- Arguments for function calls

  The value being coerced is the actual parameter, and it is coerced to the type of the formal parameter.

  For example, `&mut 42` is coerced to have type `&i8` in the following:

      fn bar(_: &i8) { }

      fn main() {
          bar(&mut 42);
      }

  For method calls, the receiver (`self` parameter) type is coerced differently, see the documentation on method-call expressions for details.

[coerce.site.constructor]

- Instantiations of struct, union, or enum variant fields

  For example, `&mut 42` is coerced to have type `&i8` in the following:

      struct Foo<'a> { x: &'a i8 }

      fn main() {
          Foo { x: &mut 42 };
      }

[coerce.site.return]

- Function results—either the final line of a block if it is not semicolon-terminated or any expression in a `return` statement

  For example, `x` is coerced to have type `&dyn Display` in the following:

      #![allow(unused)]
      fn main() {
      use std::fmt::Display;
      fn foo(x: &u32) -> &dyn Display {
          x
      }
      }

[coerce.site.subexpr]

If the expression in one of these coercion sites is a coercion-propagating expression, then the relevant sub-expressions in that expression are also coercion sites. Propagation recurses from these new coercion sites. Propagating expressions and their relevant sub-expressions are:

[coerce.site.array]

- Array literals, where the array has type `[U; n]`. Each sub-expression in the array literal is a coercion site for coercion to type `U`.

[coerce.site.repeat]

- Array literals with repeating syntax, where the array has type `[U; n]`. The repeated sub-expression is a coercion site for coercion to type `U`.

[coerce.site.tuple]

- Tuples, where a tuple is a coercion site to type `(U_0, U_1, ..., U_n)`. Each sub-expression is a coercion site to the respective type, e.g. the zeroth sub-expression is a coercion site to type `U_0`.

[coerce.site.parenthesis]

- Parenthesized sub-expressions (`(e)`): if the expression has type `U`, then the sub-expression is a coercion site to `U`.

[coerce.site.block]

- Blocks: if a block has type `U`, then the last expression in the block (if it is not semicolon-terminated) is a coercion site to `U`. This includes blocks which are part of control flow statements, such as `if`/`else`, if the block has a known type.

[coerce.types]

## Coercion types

[coerce.types.intro]

Coercion is allowed between the following types:

[coerce.types.reflexive]

- `T` to `U` if `T` is a subtype of `U` (reflexive case)

[coerce.types.transitive]

- `T_1` to `T_3` where `T_1` coerces to `T_2` and `T_2` coerces to `T_3` (transitive case)

  Note that this is not fully supported yet.

[coerce.types.mut-reborrow]

- `&mut T` to `&T`

[coerce.types.mut-pointer]

- `*mut T` to `*const T`

[coerce.types.ref-to-pointer]

- `&T` to `*const T`

[coerce.types.mut-to-pointer]

- `&mut T` to `*mut T`

[coerce.types.deref]

- `&T` or `&mut T` to `&U` if `T` implements `Deref<Target = U>`. For example:

      use std::ops::Deref;

      struct CharContainer {
          value: char,
      }

      impl Deref for CharContainer {
          type Target = char;

          fn deref<'a>(&'a self) -> &'a char {
              &self.value
          }
      }

      fn foo(arg: &char) {}

      fn main() {
          let x = &mut CharContainer { value: 'y' };
          foo(x); //&mut CharContainer is coerced to &char.
      }

[coerce.types.deref-mut]

- `&mut T` to `&mut U` if `T` implements `DerefMut<Target = U>`.

[coerce.types.unsize]

- TyCtor(`T`) to TyCtor(`U`), where TyCtor(`T`) is one of

  - `&T`
  - `&mut T`
  - `*const T`
  - `*mut T`
  - `Box<T>`

  and where `U` can be obtained from `T` by unsized coercion.

[coerce.types.fn]

- Function item types to `fn` pointers

[coerce.types.closure]

- Non capturing closures to `fn` pointers

[coerce.types.never]

- `!` to any `T`

[coerce.unsize]

### Unsized coercions

[coerce.unsize.intro]

The following coercions are called `unsized coercions`, since they relate to converting types to unsized types, and are permitted in a few cases where other coercions are not, as described above. They can still happen anywhere else a coercion can occur.

[coerce.unsize.trait]

Two traits, `Unsize` and `CoerceUnsized`, are used to assist in this process and expose it for library use. The following coercions are built-ins and, if `T` can be coerced to `U` with one of them, then an implementation of `Unsize<U>` for `T` will be provided:

[coerce.unsize.slice]

- `[T; n]` to `[T]`.

[coerce.unsize.trait-object]

- `T` to `dyn U`, when `T` implements `U + Sized`, and `U` is dyn compatible.

[coerce.unsize.trait-upcast]

- `dyn T` to `dyn U`, when `U` is one of `T`’s supertraits.
  - This allows dropping auto traits, i.e. `dyn T + Auto` to `dyn U` is allowed.
  - This allows adding auto traits if the principal trait has the auto trait as a super trait, i.e. given `trait T: U + Send {}`, `dyn T` to `dyn T + Send` or to `dyn U + Send` coercions are allowed.

[coerce.unsized.composite]

- `Foo<..., T, ...>` to `Foo<..., U, ...>`, when:
  - `Foo` is a struct.
  - `T` implements `Unsize<U>`.
  - The last field of `Foo` has a type involving `T`.
  - If that field has type `Bar<T>`, then `Bar<T>` implements `Unsize<Bar<U>>`.
  - T is not part of the type of any other fields.

[coerce.unsized.pointer]

Additionally, a type `Foo<T>` can implement `CoerceUnsized<Foo<U>>` when `T` implements `Unsize<U>` or `CoerceUnsized<Foo<U>>`. This allows it to provide an unsized coercion to `Foo<U>`.

> Note

> While the definition of the unsized coercions and their implementation has been stabilized, the traits themselves are not yet stable and therefore can’t be used directly in stable Rust.

[coerce.least-upper-bound]

## Least upper bound coercions

[coerce.least-upper-bound.intro]

In some contexts, the compiler must coerce together multiple types to try and find the most general type. This is called a “Least Upper Bound” coercion. LUB coercion is used and only used in the following situations:

- To find the common type for a series of if branches.
- To find the common type for a series of match arms.
- To find the common type for array elements.
- To find the type for the return type of a closure with multiple return statements.
- To check the type for the return type of a function with multiple return statements.

[coerce.least-upper-bound.target]

In each such case, there are a set of types `T0..Tn` to be mutually coerced to some target type `T_t`, which is unknown to start.

[coerce.least-upper-bound.computation]

Computing the LUB coercion is done iteratively. The target type `T_t` begins as the type `T0`. For each new type `Ti`, we consider whether

[coerce.least-upper-bound.computation-identity]

- If `Ti` can be coerced to the current target type `T_t`, then no change is made.

[coerce.least-upper-bound.computation-replace]

- Otherwise, check whether `T_t` can be coerced to `Ti`; if so, the `T_t` is changed to `Ti`. (This check is also conditioned on whether all of the source expressions considered thus far have implicit coercions.)

[coerce.least-upper-bound.computation-unify]

- If not, try to compute a mutual supertype of `T_t` and `Ti`, which will become the new target type.

### Examples:

    #![allow(unused)]
    fn main() {
    let (a, b, c) = (0, 1, 2);
    // For if branches
    let bar = if true {
        a
    } else if false {
        b
    } else {
        c
    };

    // For match arms
    let baw = match 42 {
        0 => a,
        1 => b,
        _ => c,
    };

    // For array elements
    let bax = [a, b, c];

    // For closure with multiple return statements
    let clo = || {
        if true {
            a
        } else if false {
            b
        } else {
            c
        }
    };
    let baz = clo();

    // For type checking of function with multiple return statements
    fn foo() -> i32 {
        let (a, b, c) = (0, 1, 2);
        match 42 {
            0 => a,
            1 => b,
            _ => c,
        }
    }
    }

In these examples, types of the `ba*` are found by LUB coercion. And the compiler checks whether LUB coercion result of `a`, `b`, `c` is `i32` in the processing of the function `foo`.

### Caveat

This description is obviously informal. Making it more precise is expected to proceed as part of a general effort to specify the Rust type checker more precisely.

[destructors]

# Destructors

[destructors.intro]

When an initialized variable or temporary goes out of scope, its destructor is run or it is dropped. Assignment also runs the destructor of its left-hand operand, if it’s initialized. If a variable has been partially initialized, only its initialized fields are dropped.

[destructors.operation]

The destructor of a type `T` consists of:

1. If `T: Drop`, calling `<T as core::ops::Drop>::drop`
2. Recursively running the destructor of all of its fields.
   - The fields of a struct are dropped in declaration order.
   - The fields of the active enum variant are dropped in declaration order.
   - The fields of a tuple are dropped in order.
   - The elements of an array or owned slice are dropped from the first element to the last.
   - The variables that a closure captures by move are dropped in an unspecified order.
   - Trait objects run the destructor of the underlying type.
   - Other types don’t result in any further drops.

[destructors.drop_in_place]

If a destructor must be run manually, such as when implementing your own smart pointer, `core::ptr::drop_in_place` can be used.

Some examples:

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);

    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("{}", self.0);
        }
    }

    let mut overwritten = PrintOnDrop("drops when overwritten");
    overwritten = PrintOnDrop("drops when scope ends");

    let tuple = (PrintOnDrop("Tuple first"), PrintOnDrop("Tuple second"));

    let moved;
    // No destructor run on assignment.
    moved = PrintOnDrop("Drops when moved");
    // Drops now, but is then uninitialized.
    moved;

    // Uninitialized does not drop.
    let uninitialized: PrintOnDrop;

    // After a partial move, only the remaining fields are dropped.
    let mut partial_move = (PrintOnDrop("first"), PrintOnDrop("forgotten"));
    // Perform a partial move, leaving only `partial_move.0` initialized.
    core::mem::forget(partial_move.1);
    // When partial_move's scope ends, only the first field is dropped.
    }

[destructors.scope]

## Drop scopes

[destructors.scope.intro]

Each variable or temporary is associated to a drop scope. When control flow leaves a drop scope all variables associated to that scope are dropped in reverse order of declaration (for variables) or creation (for temporaries).

[destructors.scope.desugaring]

Drop scopes can be determined by replacing `for`, `if`, and `while` expressions with equivalent expressions using `match`, `loop` and `break`.

[destructors.scope.operators]

Overloaded operators are not distinguished from built-in operators and binding modes are not considered.

[destructors.scope.list]

Given a function, or closure, there are drop scopes for:

[destructors.scope.function]

- The entire function

[destructors.scope.statement]

- Each statement

[destructors.scope.expression]

- Each expression

[destructors.scope.block]

- Each block, including the function body
  - In the case of a block expression, the scope for the block and the expression are the same scope.

[destructors.scope.match-arm]

- Each arm of a `match` expression

[destructors.scope.nesting]

Drop scopes are nested within one another as follows. When multiple scopes are left at once, such as when returning from a function, variables are dropped from the inside outwards.

[destructors.scope.nesting.function]

- The entire function scope is the outer most scope.

[destructors.scope.nesting.function-body]

- The function body block is contained within the scope of the entire function.

[destructors.scope.nesting.expr-statement]

- The parent of the expression in an expression statement is the scope of the statement.

[destructors.scope.nesting.let-initializer]

- The parent of the initializer of a `let` statement is the `let` statement’s scope.

[destructors.scope.nesting.statement]

- The parent of a statement scope is the scope of the block that contains the statement.

[destructors.scope.nesting.match-guard]

- The parent of the expression for a `match` guard is the scope of the arm that the guard is for.

[destructors.scope.nesting.match-arm]

- The parent of the expression after the `=>` in a `match` expression is the scope of the arm that it’s in.

[destructors.scope.nesting.match]

- The parent of the arm scope is the scope of the `match` expression that it belongs to.

[destructors.scope.nesting.other]

- The parent of all other scopes is the scope of the immediately enclosing expression.

[destructors.scope.params]

### Scopes of function parameters

All function parameters are in the scope of the entire function body, so are dropped last when evaluating the function. Each actual function parameter is dropped after any bindings introduced in that parameter’s pattern.

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    // Drops `y`, then the second parameter, then `x`, then the first parameter
    fn patterns_in_parameters(
        (x, _): (PrintOnDrop, PrintOnDrop),
        (_, y): (PrintOnDrop, PrintOnDrop),
    ) {}

    // drop order is 3 2 0 1
    patterns_in_parameters(
        (PrintOnDrop("0"), PrintOnDrop("1")),
        (PrintOnDrop("2"), PrintOnDrop("3")),
    );
    }

[destructors.scope.bindings]

### Scopes of local variables

[destructors.scope.bindings.intro]

Local variables declared in a `let` statement are associated to the scope of the block that contains the `let` statement. Local variables declared in a `match` expression are associated to the arm scope of the `match` arm that they are declared in.

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    let declared_first = PrintOnDrop("Dropped last in outer scope");
    {
        let declared_in_block = PrintOnDrop("Dropped in inner scope");
    }
    let declared_last = PrintOnDrop("Dropped first in outer scope");
    }

[destructors.scope.bindings.patterns]

Variables in patterns are dropped in reverse order of declaration within the pattern.

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    let (declared_first, declared_last) = (
        PrintOnDrop("Dropped last"),
        PrintOnDrop("Dropped first"),
    );
    }

[destructors.scope.bindings.or-patterns]

For the purpose of drop order, or-patterns declare bindings in the order given by the first subpattern.

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    // Drops `x` before `y`.
    fn or_pattern_drop_order<T>(
        (Ok([x, y]) | Err([y, x])): Result<[T; 2], [T; 2]>
    //   ^^^^^^^^^^   ^^^^^^^^^^^ This is the second subpattern.
    //   |
    //   This is the first subpattern.
    //
    //   In the first subpattern, `x` is declared before `y`. Since it is
    //   the first subpattern, that is the order used even if the second
    //   subpattern, where the bindings are declared in the opposite
    //   order, is matched.
    ) {}

    // Here we match the first subpattern, and the drops happen according
    // to the declaration order in the first subpattern.
    or_pattern_drop_order(Ok([
        PrintOnDrop("Declared first, dropped last"),
        PrintOnDrop("Declared last, dropped first"),
    ]));

    // Here we match the second subpattern, and the drops still happen
    // according to the declaration order in the first subpattern.
    or_pattern_drop_order(Err([
        PrintOnDrop("Declared last, dropped first"),
        PrintOnDrop("Declared first, dropped last"),
    ]));
    }

[destructors.scope.temporary]

### Temporary scopes

[destructors.scope.temporary.intro]

The temporary scope of an expression is the scope that is used for the temporary variable that holds the result of that expression when used in a place context, unless it is promoted.

[destructors.scope.temporary.enclosing]

Apart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following:

- The entire function.
- A statement.
- The body of an `if`, `while` or `loop` expression.
- The `else` block of an `if` expression.
- The non-pattern matching condition expression of an `if` or `while` expression, or a `match` guard.
- The body expression for a match arm.
- Each operand of a lazy boolean expression.
- The pattern-matching condition(s) and consequent body of `if` (destructors.scope.temporary.edition2024).
- The pattern-matching condition and loop body of `while`.
- The entirety of the tail expression of a block (destructors.scope.temporary.edition2024).

> Note

> The scrutinee of a `match` expression is not a temporary scope, so temporaries in the scrutinee can be dropped after the `match` expression. For example, the temporary for `1` in `match 1 { ref mut z => z };` lives until the end of the statement.

> Note

> The desugaring of a destructuring assignment restricts the temporary scope of its assigned value operand (the RHS). For details, see expr.assign.destructure.tmp-scopes.

[destructors.scope.temporary.edition2024]

> 2024 Edition differences

> The 2024 edition added two new temporary scope narrowing rules: `if let` temporaries are dropped before the `else` block, and temporaries of tail expressions of blocks are dropped immediately after the tail expression is evaluated.

Some examples:

    #![allow(unused)]
    fn main() {
    #![allow(irrefutable_let_patterns)]
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    let local_var = PrintOnDrop("local var");

    // Dropped once the condition has been evaluated
    if PrintOnDrop("If condition").0 == "If condition" {
        // Dropped at the end of the block
        PrintOnDrop("If body").0
    } else {
        unreachable!()
    };

    if let "if let scrutinee" = PrintOnDrop("if let scrutinee").0 {
        PrintOnDrop("if let consequent").0
        // `if let consequent` dropped here
    }
    // `if let scrutinee` is dropped here
    else {
        PrintOnDrop("if let else").0
        // `if let else` dropped here
    };

    while let x = PrintOnDrop("while let scrutinee").0 {
        PrintOnDrop("while let loop body").0;
        break;
        // `while let loop body` dropped here.
        // `while let scrutinee` dropped here.
    }

    // Dropped before the first ||
    (PrintOnDrop("first operand").0 == ""
    // Dropped before the )
    || PrintOnDrop("second operand").0 == "")
    // Dropped before the ;
    || PrintOnDrop("third operand").0 == "";

    // Scrutinee is dropped at the end of the function, before local variables
    // (because this is the tail expression of the function body block).
    match PrintOnDrop("Matched value in final expression") {
        // Dropped once the condition has been evaluated
        _ if PrintOnDrop("guard condition").0 == "" => (),
        _ => (),
    }
    }

[destructors.scope.operands]

### Operands

Temporaries are also created to hold the result of operands to an expression while the other operands are evaluated. The temporaries are associated to the scope of the expression with that operand. Since the temporaries are moved from once the expression is evaluated, dropping them has no effect unless one of the operands to an expression breaks out of the expression, returns, or panics.

    #![allow(unused)]
    fn main() {
    struct PrintOnDrop(&'static str);
    impl Drop for PrintOnDrop {
        fn drop(&mut self) {
            println!("drop({})", self.0);
        }
    }
    loop {
        // Tuple expression doesn't finish evaluating so operands drop in reverse order
        (
            PrintOnDrop("Outer tuple first"),
            PrintOnDrop("Outer tuple second"),
            (
                PrintOnDrop("Inner tuple first"),
                PrintOnDrop("Inner tuple second"),
                break,
            ),
            PrintOnDrop("Never created"),
        );
    }
    }

[destructors.scope.const-promotion]

### Constant promotion

Promotion of a value expression to a `'static` slot occurs when the expression could be written in a constant and borrowed, and that borrow could be dereferenced where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain interior mutability or destructors (these properties are determined based on the value where possible, e.g. `&None` always has the type `&'static Option<_>`, as it contains nothing disallowed).

[destructors.scope.lifetime-extension]

### Temporary lifetime extension

> Note

> The exact rules for temporary lifetime extension are subject to change. This is describing the current behavior only.

[destructors.scope.lifetime-extension.let]

The temporary scopes for expressions in `let` statements are sometimes extended to the scope of the block containing the `let` statement. This is done when the usual temporary scope would be too small, based on certain syntactic rules. For example:

    #![allow(unused)]
    fn main() {
    let x = &mut 0;
    // Usually a temporary would be dropped by now, but the temporary for `0` lives
    // to the end of the block.
    println!("{}", x);
    }

[destructors.scope.lifetime-extension.static]

Lifetime extension also applies to `static` and `const` items, where it makes temporaries live until the end of the program. For example:

    #![allow(unused)]
    fn main() {
    const C: &Vec<i32> = &Vec::new();
    // Usually this would be a dangling reference as the `Vec` would only
    // exist inside the initializer expression of `C`, but instead the
    // borrow gets lifetime-extended so it effectively has `'static` lifetime.
    println!("{:?}", C);
    }

[destructors.scope.lifetime-extension.sub-expressions]

If a borrow, dereference, field, or tuple indexing expression has an extended temporary scope, then so does its operand. If an indexing expression has an extended temporary scope, then the indexed expression also has an extended temporary scope.

[destructors.scope.lifetime-extension.patterns]

#### Extending based on patterns

[destructors.scope.lifetime-extension.patterns.extending]

An extending pattern is either:

- An identifier pattern that binds by reference or mutable reference.

      #![allow(unused)]
      fn main() {
      fn temp() {}
      let ref x = temp(); // Binds by reference.
      x;
      let ref mut x = temp(); // Binds by mutable reference.
      x;
      }

- A struct, tuple, tuple struct, slice, or or-pattern where at least one of the direct subpatterns is an extending pattern.

      #![allow(unused)]
      fn main() {
      use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
      static X: AtomicU64 = AtomicU64::new(0);
      struct W<T>(T);
      impl<T> Drop for W<T> { fn drop(&mut self) { X.fetch_add(1, Relaxed); } }
      let W { 0: ref x } = W(()); // Struct pattern.
      x;
      let W(ref x) = W(()); // Tuple struct pattern.
      x;
      let (W(ref x),) = (W(()),); // Tuple pattern.
      x;
      let [W(ref x), ..] = [W(())]; // Slice pattern.
      x;
      let (Ok(W(ref x)) | Err(&ref x)) = Ok(W(())); // Or pattern.
      x;
      //
      // All of the temporaries above are still live here.
      assert_eq!(0, X.load(Relaxed));
      }

So `ref x`, `V(ref x)` and `[ref x, y]` are all extending patterns, but `x`, `&ref x` and `&(ref x,)` are not.

[destructors.scope.lifetime-extension.patterns.let]

If the pattern in a `let` statement is an extending pattern then the temporary scope of the initializer expression is extended.

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // This is an extending pattern, so the temporary scope is extended.
    let ref x = *&temp(); // OK
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // This is neither an extending pattern nor an extending expression,
    // so the temporary is dropped at the semicolon.
    let &ref x = *&&temp(); // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // This is not an extending pattern but it is an extending expression,
    // so the temporary lives beyond the `let` statement.
    let &ref x = &*&temp(); // OK
    x;
    }

[destructors.scope.lifetime-extension.exprs]
Tests
Tests with this rule:

- tests/ui/lifetimes/temporary-lifetime-extension-tuple-ctor.rs

#### Extending based on expressions

[destructors.scope.lifetime-extension.exprs.extending]

For a let statement with an initializer, an extending expression is an expression which is one of the following:

- The initializer expression.
- The operand of an extending borrow expression.
- The super operands of an extending super macro call expression.
- The operand(s) of an extending array, cast, braced struct, or tuple expression.
- The arguments to an extending tuple struct or tuple enum variant constructor expression.
- The final expression of an extending block expression except for an async block expression.
- The final expression of an extending `if` expression’s consequent, `else if`, or `else` block.
- An arm expression of an extending `match` expression.

> Note

> The desugaring of a destructuring assignment makes its assigned value operand (the RHS) an extending expression within a newly-introduced block. For details, see expr.assign.destructure.tmp-ext.

So the borrow expressions in `&mut 0`, `(&1, &mut 2)`, and `Some(&mut 3)` are all extending expressions. The borrows in `&0 + &1` and `f(&mut 0)` are not.

[destructors.scope.lifetime-extension.exprs.borrows]

The operand of an extending borrow expression has its temporary scope extended.

[destructors.scope.lifetime-extension.exprs.super-macros]

The super temporaries of an extending super macro call expression have their scopes extended.

> Note

> `rustc` does not treat array repeat operands of extending array expressions as extending expressions. Whether it should is an open question.

> For details, see Rust issue #146092.

#### Examples

Here are some examples where expressions have extended temporary scopes:

    #![allow(unused)]
    fn main() {
    use core::pin::pin;
    use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
    static X: AtomicU64 = AtomicU64::new(0);
    #[derive(Debug)] struct S;
    impl Drop for S { fn drop(&mut self) { X.fetch_add(1, Relaxed); } }
    const fn temp() -> S { S }
    let x = &temp(); // Operand of borrow.
    x;
    let x = &raw const *&temp(); // Operand of raw borrow.
    assert_eq!(X.load(Relaxed), 0);
    let x = &temp() as &dyn Send; // Operand of cast.
    x;
    let x = (&*&temp(),); // Operand of tuple constructor.
    x;
    struct W<T>(T);
    let x = W(&temp()); // Argument to tuple struct constructor.
    x;
    let x = Some(&temp()); // Argument to tuple enum variant constructor.
    x;
    let x = { [Some(&temp())] }; // Final expr of block.
    x;
    let x = const { &temp() }; // Final expr of `const` block.
    x;
    let x = unsafe { &temp() }; // Final expr of `unsafe` block.
    x;
    let x = if true { &temp() } else { &temp() };
    //              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
    //           Final exprs of `if`/`else` blocks.
    x;
    let x = match () { _ => &temp() }; // `match` arm expression.
    x;
    let x = pin!(temp()); // Super operand of super macro call expression.
    x;
    let x = pin!({ &mut temp() }); // As above.
    x;
    let x = format_args!("{:?}", temp()); // As above.
    x;
    //
    // All of the temporaries above are still live here.
    assert_eq!(0, X.load(Relaxed));
    }

Here are some examples where expressions don’t have extended temporary scopes:

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Arguments to function calls are not extending expressions. The
    // temporary is dropped at the semicolon.
    let x = core::convert::identity(&temp()); // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    trait Use { fn use_temp(&self) -> &Self { self } }
    impl Use for () {}
    // Receivers of method calls are not extending expressions.
    let x = (&temp()).use_temp(); // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Scrutinees of match expressions are not extending expressions.
    let x = match &temp() { x => x }; // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Final expressions of `async` blocks are not extending expressions.
    let x = async { &temp() }; // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Final expressions of closures are not extending expressions.
    let x = || &temp(); // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Operands of loop breaks are not extending expressions.
    let x = loop { break &temp() }; // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // Operands of breaks to labels are not extending expressions.
    let x = 'a: { break 'a &temp() }; // ERROR
    x;
    }

    #![allow(unused)]
    fn main() {
    use core::pin::pin;
    fn temp() {}
    // The argument to `pin!` is only an extending expression if the call
    // is an extending expression. Since it's not, the inner block is not
    // an extending expression, so the temporaries in its trailing
    // expression are dropped immediately.
    pin!({ &temp() }); // ERROR
    }

    #![allow(unused)]
    fn main() {
    fn temp() {}
    // As above.
    format_args!("{:?}", { &temp() }); // ERROR
    }

[destructors.forget]

## Not running destructors

[destructors.manually-suppressing]

### Manually suppressing destructors

`core::mem::forget` can be used to prevent the destructor of a variable from being run, and `core::mem::ManuallyDrop` provides a wrapper to prevent a variable or field from being dropped automatically.

> Note

> Preventing a destructor from being run via `core::mem::forget` or other means is safe even if it has a type that isn’t `'static`. Besides the places where destructors are guaranteed to run as defined by this document, types may not safely rely on a destructor being run for soundness.

[destructors.process-termination]

### Process termination without unwinding

There are some ways to terminate the process without unwinding, in which case destructors will not be run.

The standard library provides `std::process::exit` and `std::process::abort` to do this explicitly. Additionally, if the panic handler is set to `abort`, panicking will always terminate the process without destructors being run.

There is one additional case to be aware of: when a panic reaches a non-unwinding ABI boundary, either no destructors will run, or all destructors up until the ABI boundary will run.

[lifetime-elision]

# Lifetime elision

Rust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice.

[lifetime-elision.function]

## Lifetime elision in functions

[lifetime-elision.function.intro]

In order to make common patterns more ergonomic, lifetime arguments can be elided in function item, function pointer, and closure trait signatures. The following rules are used to infer lifetime parameters for elided lifetimes.

[lifetime-elision.function.lifetimes-not-inferred]

It is an error to elide lifetime parameters that cannot be inferred.

[lifetime-elision.function.explicit-placeholder]

The placeholder lifetime, `'_`, can also be used to have a lifetime inferred in the same way. For lifetimes in paths, using `'_` is preferred.

[lifetime-elision.function.only-functions]

Trait object lifetimes follow different rules discussed below.

[lifetime-elision.function.implicit-lifetime-parameters]

- Each elided lifetime in the parameters becomes a distinct lifetime parameter.

[lifetime-elision.function.output-lifetime]

- If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to all elided output lifetimes.

[lifetime-elision.function.receiver-lifetime]

In method signatures there is another rule

- If the receiver has type `&Self` or `&mut Self`, then the lifetime of that reference to `Self` is assigned to all elided output lifetime parameters.

Examples:

    #![allow(unused)]
    fn main() {
    trait T {}
    trait ToCStr {}
    struct Thing<'a> {f: &'a i32}
    struct Command;

    trait Example {
    fn print1(s: &str);                                   // elided
    fn print2(s: &'_ str);                                // also elided
    fn print3<'a>(s: &'a str);                            // expanded

    fn debug1(lvl: usize, s: &str);                       // elided
    fn debug2<'a>(lvl: usize, s: &'a str);                // expanded

    fn substr1(s: &str, until: usize) -> &str;            // elided
    fn substr2<'a>(s: &'a str, until: usize) -> &'a str;  // expanded

    fn get_mut1(&mut self) -> &mut dyn T;                 // elided
    fn get_mut2<'a>(&'a mut self) -> &'a mut dyn T;       // expanded

    fn args1<T: ToCStr>(&mut self, args: &[T]) -> &mut Command;                  // elided
    fn args2<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded

    fn other_args1<'a>(arg: &str) -> &'a str;             // elided
    fn other_args2<'a, 'b>(arg: &'b str) -> &'a str;      // expanded

    fn new1(buf: &mut [u8]) -> Thing<'_>;                 // elided - preferred
    fn new2(buf: &mut [u8]) -> Thing;                     // elided
    fn new3<'a>(buf: &'a mut [u8]) -> Thing<'a>;          // expanded
    }

    type FunPtr1 = fn(&str) -> &str;                      // elided
    type FunPtr2 = for<'a> fn(&'a str) -> &'a str;        // expanded

    type FunTrait1 = dyn Fn(&str) -> &str;                // elided
    type FunTrait2 = dyn for<'a> Fn(&'a str) -> &'a str;  // expanded
    }

    #![allow(unused)]
    fn main() {
    // The following examples show situations where it is not allowed to elide the
    // lifetime parameter.

    trait Example {
    // Cannot infer, because there are no parameters to infer from.
    fn get_str() -> &str;                                 // ILLEGAL

    // Cannot infer, ambiguous if it is borrowed from the first or second parameter.
    fn frob(s: &str, t: &str) -> &str;                    // ILLEGAL
    }
    }

[lifetime-elision.trait-object]

## Default trait object lifetimes

[lifetime-elision.trait-object.intro]

The assumed lifetime of references held by a trait object is called its default object lifetime bound. These were defined in RFC 599 and amended in RFC 1156.

[lifetime-elision.trait-object.explicit-bound]

These default object lifetime bounds are used instead of the lifetime parameter elision rules defined above when the lifetime bound is omitted entirely.

[lifetime-elision.trait-object.explicit-placeholder]

If `'_` is used as the lifetime bound then the bound follows the usual elision rules.

[lifetime-elision.trait-object.containing-type]

If the trait object is used as a type argument of a generic type then the containing type is first used to try to infer a bound.

[lifetime-elision.trait-object.containing-type-unique]

- If there is a unique bound from the containing type then that is the default

[lifetime-elision.trait-object.containing-type-explicit]

- If there is more than one bound from the containing type then an explicit bound must be specified

[lifetime-elision.trait-object.trait-bounds]

If neither of those rules apply, then the bounds on the trait are used:

[lifetime-elision.trait-object.trait-unique]

- If the trait is defined with a single lifetime bound then that bound is used.

[lifetime-elision.trait-object.static-lifetime]

- If `'static` is used for any lifetime bound then `'static` is used.

[lifetime-elision.trait-object.default]

- If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is `'static` outside of expressions.

    #![allow(unused)]
    fn main() {
    // For the following trait...
    trait Foo { }

    // These two are the same because Box<T> has no lifetime bound on T
    type T1 = Box<dyn Foo>;
    type T2 = Box<dyn Foo + 'static>;

    // ...and so are these:
    impl dyn Foo {}
    impl dyn Foo + 'static {}

    // ...so are these, because &'a T requires T: 'a
    type T3<'a> = &'a dyn Foo;
    type T4<'a> = &'a (dyn Foo + 'a);

    // std::cell::Ref<'a, T> also requires T: 'a, so these are the same
    type T5<'a> = std::cell::Ref<'a, dyn Foo>;
    type T6<'a> = std::cell::Ref<'a, dyn Foo + 'a>;
    }

    #![allow(unused)]
    fn main() {
    // This is an example of an error.
    trait Foo { }
    struct TwoBounds<'a, 'b, T: ?Sized + 'a + 'b> {
        f1: &'a i32,
        f2: &'b i32,
        f3: T,
    }
    type T7<'a, 'b> = TwoBounds<'a, 'b, dyn Foo>;
    //                                  ^^^^^^^
    // Error: the lifetime bound for this object type cannot be deduced from context
    }

[lifetime-elision.trait-object.innermost-type]

Note that the innermost object sets the bound, so `&'a Box<dyn Foo>` is still `&'a Box<dyn Foo + 'static>`.

    #![allow(unused)]
    fn main() {
    // For the following trait...
    trait Bar<'a>: 'a { }

    // ...these two are the same:
    type T1<'a> = Box<dyn Bar<'a>>;
    type T2<'a> = Box<dyn Bar<'a> + 'a>;

    // ...and so are these:
    impl<'a> dyn Bar<'a> {}
    impl<'a> dyn Bar<'a> + 'a {}
    }

[lifetime-elision.const-static]

## `const` and `static` elision

[lifetime-elision.const-static.implicit-static]

Both constant and static declarations of reference types have implicit `'static` lifetimes unless an explicit lifetime is specified. As such, the constant declarations involving `'static` above may be written without the lifetimes.

    #![allow(unused)]
    fn main() {
    // STRING: &'static str
    const STRING: &str = "bitstring";

    struct BitsNStrings<'a> {
        mybits: [u32; 2],
        mystring: &'a str,
    }

    // BITS_N_STRINGS: BitsNStrings<'static>
    const BITS_N_STRINGS: BitsNStrings<'_> = BitsNStrings {
        mybits: [1, 2],
        mystring: STRING,
    };
    }

[lifetime-elision.const-static.fn-references]

Note that if the `static` or `const` items include function or closure references, which themselves include references, the compiler will first try the standard elision rules. If it is unable to resolve the lifetimes by its usual rules, then it will error. By way of example:

    #![allow(unused)]
    fn main() {
    struct Foo;
    struct Bar;
    struct Baz;
    fn somefunc(a: &Foo, b: &Bar, c: &Baz) -> usize {42}
    // Resolved as `for<'a> fn(&'a str) -> &'a str`.
    const RESOLVED_SINGLE: fn(&str) -> &str = |x| x;

    // Resolved as `for<'a, 'b, 'c> Fn(&'a Foo, &'b Bar, &'c Baz) -> usize`.
    const RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc;
    }

    #![allow(unused)]
    fn main() {
    struct Foo;
    struct Bar;
    struct Baz;
    fn somefunc<'a,'b>(a: &'a Foo, b: &'b Bar) -> &'a Baz {unimplemented!()}
    // There is insufficient information to bound the return reference lifetime
    // relative to the argument lifetimes, so this is an error.
    const RESOLVED_STATIC: &dyn Fn(&Foo, &Bar) -> &Baz = &somefunc;
    //                                            ^
    // this function's return type contains a borrowed value, but the signature
    // does not say whether it is borrowed from argument 1 or argument 2
    }

[lang-types]

# Special types and traits

[lang-types.intro]

Certain types and traits that exist in the standard library are known to the Rust compiler. This chapter documents the special features of these types and traits.

[lang-types.box]

## `Box<T>`

[lang-types.box.intro]

`Box<T>` has a few special features that Rust doesn’t currently allow for user defined types.

[lang-types.box.deref]

- The dereference operator for `Box<T>` produces a place which can be moved from. This means that the `*` operator and the destructor of `Box<T>` are built-in to the language.

[lang-types.box.receiver]

- Methods can take `Box<Self>` as a receiver.

[lang-types.box.fundamental]

- A trait may be implemented for `Box<T>` in the same crate as `T`, which the orphan rules prevent for other generic types.

[lang-types.rc]

## `Rc<T>`

[lang-types.rc.receiver]

Methods can take `Rc<Self>` as a receiver.

[lang-types.arc]

## `Arc<T>`

[lang-types.arc.receiver]

Methods can take `Arc<Self>` as a receiver.

[lang-types.pin]

## `Pin<P>`

[lang-types.pin.receiver]

Methods can take `Pin<P>` as a receiver.

[lang-types.unsafe-cell]

## `UnsafeCell<T>`

[lang-types.unsafe-cell.interior-mut]

`std::cell::UnsafeCell<T>` is used for interior mutability. It ensures that the compiler doesn’t perform optimisations that are incorrect for such types.

[lang-types.unsafe-cell.read-only-alloc]

It also ensures that `static` items which have a type with interior mutability aren’t placed in memory marked as read only.

[lang-types.phantom-data]

## `PhantomData<T>`

`std::marker::PhantomData<T>` is a zero-sized, minimum alignment, type that is considered to own a `T` for the purposes of variance, drop check, and auto traits.

[lang-types.ops]

## Operator traits

The traits in `std::ops` and `std::cmp` are used to overload operators, indexing expressions, and call expressions.

[lang-types.deref]

## `Deref` and `DerefMut`

As well as overloading the unary `*` operator, `Deref` and `DerefMut` are also used in method resolution and deref coercions.

[lang-types.drop]

## `Drop`

The `Drop` trait provides a destructor, to be run whenever a value of this type is to be destroyed.

[lang-types.copy]

## `Copy`

[lang-types.copy.intro]

The `Copy` trait changes the semantics of a type implementing it.

[lang-types.copy.behavior]

Values whose type implements `Copy` are copied rather than moved upon assignment.

[lang-types.copy.constraint]

`Copy` can only be implemented for types which do not implement `Drop`, and whose fields are all `Copy`. For enums, this means all fields of all variants have to be `Copy`. For unions, this means all variants have to be `Copy`.

[lang-types.copy.builtin-types]

`Copy` is implemented by the compiler for

[lang-types.copy.tuple]

- Tuples of `Copy` types

[lang-types.copy.fn-pointer]

- Function pointers

[lang-types.copy.fn-item]

- Function items

[lang-types.copy.closure]

- Closures that capture no values or that only capture values of `Copy` types

[lang-types.clone]

## `Clone`

[lang-types.clone.intro]

The `Clone` trait is a supertrait of `Copy`, so it also needs compiler generated implementations.

[lang-types.clone.builtin-types]

It is implemented by the compiler for the following types:

[lang-types.clone.builtin-copy]

- Types with a built-in `Copy` implementation (see above)

[lang-types.clone.tuple]

- Tuples of `Clone` types

[lang-types.clone.closure]

- Closures that only capture values of `Clone` types or capture no values from the environment

[lang-types.send]

## `Send`

The `Send` trait indicates that a value of this type is safe to send from one thread to another.

[lang-types.sync]

## `Sync`

[lang-types.sync.intro]

The `Sync` trait indicates that a value of this type is safe to share between multiple threads.

[lang-types.sync.static-constraint]

This trait must be implemented for all types used in immutable `static` items.

[lang-types.termination]

## `Termination`

The `Termination` trait indicates the acceptable return types for the main function and test functions.

[lang-types.auto-traits]

## Auto traits

The `Send`, `Sync`, `Unpin`, `UnwindSafe`, and `RefUnwindSafe` traits are auto traits. Auto traits have special properties.

[lang-types.auto-traits.auto-impl]

If no explicit implementation or negative implementation is written out for an auto trait for a given type, then the compiler implements it automatically according to the following rules:

[lang-types.auto-traits.builtin-composite]

- `&T`, `&mut T`, `*const T`, `*mut T`, `[T; n]`, and `[T]` implement the trait if `T` does.

[lang-types.auto-traits.fn-item-pointer]

- Function item types and function pointers automatically implement the trait.

[lang-types.auto-traits.aggregate]

- Structs, enums, unions, and tuples implement the trait if all of their fields do.

[lang-types.auto-traits.closure]

- Closures implement the trait if the types of all of their captures do. A closure that captures a `T` by shared reference and a `U` by value implements any auto traits that both `&T` and `U` do.

[lang-types.auto-traits.generic-impl]

For generic types (counting the built-in types above as generic over `T`), if a generic implementation is available, then the compiler does not automatically implement it for types that could use the implementation except that they do not meet the requisite trait bounds. For instance, the standard library implements `Send` for all `&T` where `T` is `Sync`; this means that the compiler will not implement `Send` for `&T` if `T` is `Send` but not `Sync`.

[lang-types.auto-traits.negative]

Auto traits can also have negative implementations, shown as `impl !AutoTrait for T` in the standard library documentation, that override the automatic implementations. For example `*mut T` has a negative implementation of `Send`, and so `*mut T` is not `Send`, even if `T` is. There is currently no stable way to specify additional negative implementations; they exist only in the standard library.

[lang-types.auto-traits.trait-object-marker]

Auto traits may be added as an additional bound to any trait object, even though normally only one trait is allowed. For instance, `Box<dyn Debug + Send + UnwindSafe>` is a valid type.

[lang-types.sized]

## `Sized`

[lang-types.sized.intro]

The `Sized` trait indicates that the size of this type is known at compile-time; that is, it’s not a dynamically sized type.

[lang-types.sized.implicit-sized]

Type parameters (except `Self` in traits) are `Sized` by default, as are associated types.

[lang-types.sized.implicit-impl]

`Sized` is always implemented automatically by the compiler, not by implementation items.

[lang-types.sized.relaxation]

These implicit `Sized` bounds may be relaxed by using the special `?Sized` bound.

[names]

# Names

[names.intro]

An entity is a language construct that can be referred to in some way within the source program, usually via a path. Entities include types, items, generic parameters, variable bindings, loop labels, lifetimes, fields, attributes, and lints.

A declaration is a syntactical construct that can introduce a name to refer to an entity. Entity names are valid within a scope — a region of source text where that name may be referenced.

Some entities are explicitly declared in the source code, and some are implicitly declared as part of the language or compiler extensions.

Paths are used to refer to an entity, possibly in another module or type.

Lifetimes and loop labels use a dedicated syntax using a leading quote.

Names are segregated into different namespaces, allowing entities in different namespaces to share the same name without conflict.

Name resolution is the compile-time process of tying paths, identifiers, and labels to entity declarations.

Access to certain names may be restricted based on their visibility.

[names.explicit]

## Explicitly declared entities

[names.explicit.list]

Entities that explicitly introduce a name in the source code are:

[names.explicit.item-decl]

- Items:
  - Module declarations
  - External crate declarations
  - Use declarations
  - Function declarations and function parameters
  - Type aliases
  - struct, union, enum, enum variant declarations, and their named fields
  - Constant item declarations
  - Static item declarations
  - Trait item declarations and their associated items
  - External block items
  - `macro_rules` declarations and matcher metavariables
  - Implementation associated items

[names.explicit.expr]

- Expressions:
  - Closure parameters
  - `while let` pattern bindings
  - `for` pattern bindings
  - `if let` pattern bindings
  - `match` pattern bindings
  - Loop labels

[names.explicit.generics]

- Generic parameters

[names.explicit.higher-ranked-bounds]

- Higher ranked trait bounds

[names.explicit.binding]

- `let` statement pattern bindings

[names.explicit.macro_use]

- The `macro_use` attribute can introduce macro names from another crate

[names.explicit.macro_export]

- The `macro_export` attribute can introduce an alias for the macro into the crate root

[names.explicit.macro-invocation]

Additionally, macro invocations and attributes can introduce names by expanding to one of the above items.

[names.implicit]

## Implicitly declared entities

[names.implicit.list]

The following entities are implicitly defined by the language, or are introduced by compiler options and extensions:

[names.implicit.primitive-types]

- Language prelude:
  - Boolean type — `bool`
  - Textual types — `char` and `str`
  - Integer types — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
  - Machine-dependent integer types — `usize` and `isize`
  - floating-point types — `f32` and `f64`

[names.implicit.builtin-attributes]

- Built-in attributes

[names.implicit.prelude]

- Standard library prelude items, attributes, and macros

[names.implicit.stdlib]

- Standard library crates in the root module

[names.implicit.extern-prelude]

- External crates linked by the compiler

[names.implicit.tool-attributes]

- Tool attributes

[names.implicit.lints]

- Lints and tool lint attributes

[names.implicit.derive-helpers]

- Derive helper attributes are valid within an item without being explicitly imported

[names.implicit.lifetime-static]

- The `'static` lifetime

[names.implicit.root]

Additionally, the crate root module does not have a name, but can be referred to with certain path qualifiers or aliases.

[names.namespaces]

# Namespaces

[names.namespaces.intro]

A namespace is a logical grouping of declared names. Names are segregated into separate namespaces based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.

There are several different namespaces that each contain different kinds of entities. The usage of a name will look for the declaration of that name in different namespaces, based on the context, as described in the name resolution chapter.

[names.namespaces.kinds]

The following is a list of namespaces, with their corresponding entities:

- Type Namespace
  - Module declarations
  - External crate declarations
  - External crate prelude items
  - Struct, union, enum, enum variant declarations
  - Trait item declarations
  - Type aliases
  - Associated type declarations
  - Built-in types: boolean, numeric, and textual
  - Generic type parameters
  - `Self` type
  - Tool attribute modules
- Value Namespace
  - Function declarations
  - Constant item declarations
  - Static item declarations
  - Struct constructors
  - Enum variant constructors
  - `Self` constructors
  - Generic const parameters
  - Associated const declarations
  - Associated function declarations
  - Local bindings — `let`, `if let`, `while let`, `for`, `match` arms, function parameters, closure parameters
  - Captured closure variables
- Macro Namespace
  - `macro_rules` declarations
  - Built-in attributes
  - Tool attributes
  - Function-like procedural macros
  - Derive macros
  - Derive macro helpers
  - Attribute macros
- Lifetime Namespace
  - Generic lifetime parameters
- Label Namespace
  - Loop labels
  - Block labels

An example of how overlapping names in different namespaces can be used unambiguously:

    #![allow(unused)]
    fn main() {
    // Foo introduces a type in the type namespace and a constructor in the value
    // namespace.
    struct Foo(u32);

    // The `Foo` macro is declared in the macro namespace.
    macro_rules! Foo {
        () => {};
    }

    // `Foo` in the `f` parameter type refers to `Foo` in the type namespace.
    // `'Foo` introduces a new lifetime in the lifetime namespace.
    fn example<'Foo>(f: Foo) {
        // `Foo` refers to the `Foo` constructor in the value namespace.
        let ctor = Foo;
        // `Foo` refers to the `Foo` macro in the macro namespace.
        Foo!{}
        // `'Foo` introduces a label in the label namespace.
        'Foo: loop {
            // `'Foo` refers to the `'Foo` lifetime parameter, and `Foo`
            // refers to the type namespace.
            let x: &'Foo Foo;
            // `'Foo` refers to the label.
            break 'Foo;
        }
    }
    }

[names.namespaces.without]

## Named entities without a namespace

The following entities have explicit names, but the names are not a part of any specific namespace.

### Fields

[names.namespaces.without.fields]

Even though struct, enum, and union fields are named, the named fields do not live in an explicit namespace. They can only be accessed via a field expression, which only inspects the field names of the specific type being accessed.

### Use declarations

[names.namespaces.without.use]

A use declaration has named aliases that it imports into scope, but the `use` item itself does not belong to a specific namespace. Instead, it can introduce aliases into multiple namespaces, depending on the item kind being imported.

[names.namespaces.sub-namespaces]

## Sub-namespaces

[names.namespaces.sub-namespaces.intro]

The macro namespace is split into two sub-namespaces: one for bang-style macros and one for attributes. When an attribute is resolved, any bang-style macros in scope will be ignored. And conversely resolving a bang-style macro will ignore attribute macros in scope. This prevents one style from shadowing another.

For example, the `cfg` attribute and the `cfg` macro are two different entities with the same name in the macro namespace, but they can still be used in their respective context.

> Note

> `use` imports still cannot create duplicate bindings of the same name in a module or block, regardless of sub-namespace.

>     #[macro_export]
>     macro_rules! mymac {
>         () => {};
>     }

>     use myattr::mymac; // error[E0252]: the name `mymac` is defined multiple times.

[names.scopes]

# Scopes

[names.scopes.intro]

A scope is the region of source text where a named entity may be referenced with that name. The following sections provide details on the scoping rules and behavior, which depend on the kind of entity and where it is declared. The process of how names are resolved to entities is described in the name resolution chapter. More information on “drop scopes” used for the purpose of running destructors may be found in the destructors chapter.

[names.scopes.items]

## Item scopes

[names.scopes.items.module]

The name of an item declared directly in a module has a scope that extends from the start of the module to the end of the module. These items are also members of the module and can be referred to with a path leading from their module.

[names.scopes.items.statement]

The name of an item declared as a statement has a scope that extends from the start of the block the item statement is in until the end of the block.

[names.scopes.items.duplicate]

It is an error to introduce an item with a duplicate name of another item in the same namespace within the same module or block. Asterisk glob imports have special behavior for dealing with duplicate names and shadowing, see the linked chapter for more details.

[names.scopes.items.shadow-prelude]

Items in a module may shadow items in a prelude.

[names.scopes.items.nested-modules]

Item names from outer modules are not in scope within a nested module. A path may be used to refer to an item in another module.

[names.scopes.associated-items]

### Associated item scopes

[names.scopes.associated-items.scope]

Associated items are not scoped and can only be referred to by using a path leading from the type or trait they are associated with. Methods can also be referred to via call expressions.

[names.scopes.associated-items.duplicate]

Similar to items within a module or block, it is an error to introduce an item within a trait or implementation that is a duplicate of another item in the trait or impl in the same namespace.

[names.scopes.pattern-bindings]

## Pattern binding scopes

The scope of a local variable pattern binding depends on where it is used:

[names.scopes.pattern-bindings.let]

- `let` statement bindings range from just after the `let` statement until the end of the block where it is declared.

[names.scopes.pattern-bindings.parameter]

- Function parameter bindings are within the body of the function.

[names.scopes.pattern-bindings.closure]

- Closure parameter bindings are within the closure body.

[names.scopes.pattern-bindings.loop]

- `for` bindings are within the loop body.

[names.scopes.pattern-bindings.let-chains]

- `if let` and `while let` bindings are valid in the following conditions as well as the consequent block.

[names.scopes.pattern-bindings.match-arm]

- `match` arms bindings are within the match guard and the match arm expression.

[names.scopes.pattern-bindings.items]

Local variable scopes do not extend into item declarations.

### Pattern binding shadowing

[names.scopes.pattern-bindings.shadow]

Pattern bindings are allowed to shadow any name in scope with the following exceptions which are an error:

- Const generic parameters
- Static items
- Const items
- Constructors for structs and enums

The following example illustrates how local bindings can shadow item declarations:

    #![allow(unused)]
    fn main() {
    fn shadow_example() {
        // Since there are no local variables in scope yet, this resolves to the function.
        foo(); // prints `function`
        let foo = || println!("closure");
        fn foo() { println!("function"); }
        // This resolves to the local closure since it shadows the item.
        foo(); // prints `closure`
    }
    }

[names.scopes.generic-parameters]

## Generic parameter scopes

[names.scopes.generic-parameters.param-list]

Generic parameters are declared in a GenericParams list. The scope of a generic parameter is within the item it is declared on.

[names.scopes.generic-parameters.order-independent]

All parameters are in scope within the generic parameter list regardless of the order they are declared. The following shows some examples where a parameter may be referenced before it is declared:

    #![allow(unused)]
    fn main() {
    // The 'b bound is referenced before it is declared.
    fn params_scope<'a: 'b, 'b>() {}

    trait SomeTrait<const Z: usize> {}
    // The const N is referenced in the trait bound before it is declared.
    fn f<T: SomeTrait<N>, const N: usize>() {}
    }

[names.scopes.generic-parameters.bounds]

Generic parameters are also in scope for type bounds and where clauses, for example:

    #![allow(unused)]
    fn main() {
    trait SomeTrait<'a, T> {}
    // The <'a, U> for `SomeTrait` refer to the 'a and U parameters of `bounds_scope`.
    fn bounds_scope<'a, T: SomeTrait<'a, U>, U>() {}

    fn where_scope<'a, T, U>()
        where T: SomeTrait<'a, U>
    {}
    }

[names.scopes.generic-parameters.inner-items]

It is an error for items declared inside a function to refer to a generic parameter from their outer scope.

    #![allow(unused)]
    fn main() {
    fn example<T>() {
        fn inner(x: T) {} // ERROR: can't use generic parameters from outer function
    }
    }

### Generic parameter shadowing

[names.scopes.generic-parameters.shadow]

It is an error to shadow a generic parameter with the exception that items declared within functions are allowed to shadow generic parameter names from the function.

    #![allow(unused)]
    fn main() {
    fn example<'a, T, const N: usize>() {
        // Items within functions are allowed to shadow generic parameter in scope.
        fn inner_lifetime<'a>() {} // OK
        fn inner_type<T>() {} // OK
        fn inner_const<const N: usize>() {} // OK
    }
    }

    #![allow(unused)]
    fn main() {
    trait SomeTrait<'a, T, const N: usize> {
        fn example_lifetime<'a>() {} // ERROR: 'a is already in use
        fn example_type<T>() {} // ERROR: T is already in use
        fn example_const<const N: usize>() {} // ERROR: N is already in use
        fn example_mixed<const T: usize>() {} // ERROR: T is already in use
    }
    }

[names.scopes.lifetimes]

### Lifetime scopes

Lifetime parameters are declared in a GenericParams list and higher-ranked trait bounds.

[names.scopes.lifetimes.special]

The `'static` lifetime and placeholder lifetime `'_` have a special meaning and cannot be declared as a parameter.

#### Lifetime generic parameter scopes

[names.scopes.lifetimes.generic]

Constant and static items and const contexts only ever allow `'static` lifetime references, so no other lifetime may be in scope within them. Associated consts do allow referring to lifetimes declared in their trait or implementation.

#### Higher-ranked trait bound scopes

[names.scopes.lifetimes.higher-ranked]

The scope of a lifetime parameter declared as a higher-ranked trait bound depends on the scenario where it is used.

- As a TypeBoundWhereClauseItem the declared lifetimes are in scope in the type and the type bounds.
- As a TraitBound the declared lifetimes are in scope within the bound type path.
- As a BareFunctionType the declared lifetimes are in scope within the function parameters and return type.

    #![allow(unused)]
    fn main() {
    trait Trait<'a>{}

    fn where_clause<T>()
        // 'a is in scope in both the type and the type bounds.
        where for <'a> &'a T: Trait<'a>
    {}

    fn bound<T>()
        // 'a is in scope within the bound.
        where T: for <'a> Trait<'a>
    {}

    struct Example<'a> {
        field: &'a u32
    }

    // 'a is in scope in both the parameters and return type.
    type FnExample = for<'a> fn(x: Example<'a>) -> Example<'a>;
    }

#### Impl trait restrictions

[names.scopes.lifetimes.impl-trait]

Impl trait types can only reference lifetimes declared on a function or implementation.

    #![allow(unused)]
    fn main() {
    trait Trait1 {
        type Item;
    }
    trait Trait2<'a> {}

    struct Example;

    impl Trait1 for Example {
        type Item = Element;
    }

    struct Element;
    impl<'a> Trait2<'a> for Element {}

    // The `impl Trait2` here is not allowed to refer to 'b but it is allowed to
    // refer to 'a.
    fn foo<'a>() -> impl for<'b> Trait1<Item = impl Trait2<'a> + use<'a>> {
        // ...
       Example
    }
    }

[names.scopes.loop-label]

## Loop label scopes

[names.scopes.loop-label.scope]

Loop labels may be declared by a loop expression. The scope of a loop label is from the point it is declared till the end of the loop expression. The scope does not extend into items, closures, async blocks, const arguments, const contexts, and the iterator expression of the defining `for` loop.

    #![allow(unused)]
    fn main() {
    'a: for n in 0..3 {
        if n % 2 == 0 {
            break 'a;
        }
        fn inner() {
            // Using 'a here would be an error.
            // break 'a;
        }
    }

    // The label is in scope for the expression of `while` loops.
    'a: while break 'a {}         // Loop does not run.
    'a: while let _ = break 'a {} // Loop does not run.

    // The label is not in scope in the defining `for` loop:
    'a: for outer in 0..5 {
        // This will break the outer loop, skipping the inner loop and stopping
        // the outer loop.
        'a: for inner in { break 'a; 0..1 } {
            println!("{}", inner); // This does not run.
        }
        println!("{}", outer); // This does not run, either.
    }

    }

[names.scopes.loop-label.shadow]

Loop labels may shadow labels of the same name in outer scopes. References to a label refer to the closest definition.

    #![allow(unused)]
    fn main() {
    // Loop label shadowing example.
    'a: for outer in 0..5 {
        'a: for inner in 0..5 {
            // This terminates the inner loop, but the outer loop continues to run.
            break 'a;
        }
    }
    }

[names.scopes.prelude]

## Prelude scopes

[names.scopes.prelude.intro]

Preludes bring entities into scope of every module. The entities are not members of the module, but are implicitly queried during name resolution.

[names.scopes.prelude.shadow]

The prelude names may be shadowed by declarations in a module.

[names.scopes.prelude.layers]

The preludes are layered such that one shadows another if they contain entities of the same name. The order that preludes may shadow other preludes is the following where earlier entries may shadow later ones:

1. Extern prelude
2. Tool prelude
3. `macro_use` prelude
4. Standard library prelude
5. Language prelude

[names.scopes.macro_rules]

## `macro_rules` scopes

The scope of `macro_rules` macros is described in the Macros By Example chapter. The behavior depends on the use of the `macro_use` and `macro_export` attributes.

[names.scopes.derive]

## Derive macro helper attributes

[names.scopes.derive.scope]

Derive macro helper attributes are in scope in the item where their corresponding `derive` attribute is specified. The scope extends from just after the `derive` attribute to the end of the item.

[names.scopes.derive.shadow]

Helper attributes shadow other attributes of the same name in scope.

[names.scopes.self]

## `Self` scope

[names.scopes.self.intro]

Although `Self` is a keyword with special meaning, it interacts with name resolution in a way similar to normal names.

[names.scopes.self.def-scope]

The implicit `Self` type in the definition of a struct, enum, union, trait, or implementation is treated similarly to a generic parameter, and is in scope in the same way as a generic type parameter.

[names.scopes.self.impl-scope]

The implicit `Self` constructor in the value namespace of an implementation is in scope within the body of the implementation (the implementation’s associated items).

    #![allow(unused)]
    fn main() {
    // Self type within struct definition.
    struct Recursive {
        f1: Option<Box<Self>>
    }

    // Self type within generic parameters.
    struct SelfGeneric<T: Into<Self>>(T);

    // Self value constructor within an implementation.
    struct ImplExample();
    impl ImplExample {
        fn example() -> Self { // Self type
            Self() // Self value constructor
        }
    }
    }

[names.preludes]

# Preludes

[names.preludes.intro]

A prelude is a collection of names that are automatically brought into scope of every module in a crate.

These prelude names are not part of the module itself: they are implicitly queried during name resolution. For example, even though something like `Box` is in scope in every module, you cannot refer to it as `self::Box` because it is not a member of the current module.

[names.preludes.kinds]

There are several different preludes:

- Standard library prelude
- Extern prelude
- Language prelude
- `macro_use` prelude
- Tool prelude

[names.preludes.std]

## Standard library prelude

[names.preludes.std.intro]

Each crate has a standard library prelude, which consists of the names from a single standard library module.

[names.preludes.std.module]

The module used depends on the crate’s edition, and on whether the `no_std` attribute is applied to the crate:

Edition | `no_std` not applied | `no_std` applied
--- | --- | ---
2015 | `std::prelude::rust_2015` | `core::prelude::rust_2015`
2018 | `std::prelude::rust_2018` | `core::prelude::rust_2018`
2021 | `std::prelude::rust_2021` | `core::prelude::rust_2021`
2024 | `std::prelude::rust_2024` | `core::prelude::rust_2024`

> Note

> `std::prelude::rust_2015` and `std::prelude::rust_2018` have the same contents as `std::prelude::v1`.

> `core::prelude::rust_2015` and `core::prelude::rust_2018` have the same contents as `core::prelude::v1`.

[names.preludes.extern]

## Extern prelude

[names.preludes.extern.intro]

External crates imported with `extern crate` in the root module or provided to the compiler (as with the `--extern` flag with `rustc`) are added to the extern prelude. If imported with an alias such as `extern crate orig_name as new_name`, then the symbol `new_name` is instead added to the prelude.

[names.preludes.extern.core]

The `core` crate is always added to the extern prelude.

[names.preludes.extern.std]

The `std` crate is added as long as the `no_std` attribute is not specified in the crate root.

[names.preludes.extern.edition2018]

> 2018 Edition differences

> In the 2015 edition, crates in the extern prelude cannot be referenced via use declarations, so it is generally standard practice to include `extern crate` declarations to bring them into scope.

> Beginning in the 2018 edition, use declarations can reference crates in the extern prelude, so it is considered unidiomatic to use `extern crate`.

> Note

> Additional crates that ship with `rustc`, such as `alloc`, and `test`, are not automatically included with the `--extern` flag when using Cargo. They must be brought into scope with an `extern crate` declaration, even in the 2018 edition.

>     #![allow(unused)]
>     fn main() {
>     extern crate alloc;
>     use alloc::rc::Rc;
>     }

> Cargo does bring in `proc_macro` to the extern prelude for proc-macro crates only.

[names.preludes.extern.no_std]

### The `no_std` attribute

[names.preludes.extern.no_std.intro]

The `no_std` attribute causes the `std` crate to not be linked automatically, the standard library prelude to instead use the `core` prelude, and the `macro_use` prelude to instead use the macros exported from the `core` crate.

> Example

>     #![no_std]

> Note

> Using `no_std` is useful when either the crate is targeting a platform that does not support the standard library or is purposefully not using the capabilities of the standard library. Those capabilities are mainly dynamic memory allocation (e.g. `Box` and `Vec`) and file and network capabilities (e.g. `std::fs` and `std::io`).

> Warning

> Using `no_std` does not prevent the standard library from being linked. It is still valid to write `extern crate std` in the crate or in one of its dependencies; this will cause the compiler to link the `std` crate into the program.

[names.preludes.extern.no_std.syntax]

The `no_std` attribute uses the MetaWord syntax.

[names.preludes.extern.no_std.allowed-positions]

The `no_std` attribute may only be applied to the crate root.

[names.preludes.extern.no_std.duplicates]

The `no_std` attribute may be used any number of times on a form.

> Note

> `rustc` lints against any use following the first.

[names.preludes.extern.no_std.module]

The `no_std` attribute changes the standard library prelude to use the `core` prelude instead of the `std` prelude.

[names.preludes.extern.no_std.macro_use]

By default, all macros exported from the `std` crate are added to the `macro_use` prelude. If the `no_std` attribute is specified, then all macros exported from the `core` crate are placed into the `macro_use` prelude instead.

[names.preludes.extern.no_std.edition2018]

> 2018 Edition differences

> Before the 2018 edition, `std` is injected into the crate root by default. If `no_std` is specified, `core` is injected instead. Starting with the 2018 edition, regardless of `no_std` being specified, neither is injected into the crate root.

[names.preludes.lang]

## Language prelude

[names.preludes.lang.intro]

The language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope.

[names.preludes.lang.entities]

It includes the following:

- Type namespace
  - Boolean type — `bool`
  - Textual types — `char` and `str`
  - Integer types — `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
  - Machine-dependent integer types — `usize` and `isize`
  - floating-point types — `f32` and `f64`
- Macro namespace
  - Built-in attributes
  - Built-in derive macros

[names.preludes.macro_use]

## `macro_use` prelude

[names.preludes.macro_use.intro]

The `macro_use` prelude includes macros from external crates that were imported by the `macro_use` attribute applied to an `extern crate`.

[names.preludes.tool]

## Tool prelude

[names.preludes.tool.intro]

The tool prelude includes tool names for external tools in the type namespace. See the tool attributes section for more details.

[names.preludes.no_implicit_prelude]

## The `no_implicit_prelude` attribute

[names.preludes.no_implicit_prelude.intro]

The `no_implicit_prelude` attribute is used to prevent implicit preludes from being brought into scope.

> Example

>     #![allow(unused)]
>     fn main() {
>     // The attribute can be applied to the crate root to affect
>     // all modules.
>     #![no_implicit_prelude]

>     // Or it can be applied to a module to only affect that module
>     // and its descendants.
>     #[no_implicit_prelude]
>     mod example {
>         // ...
>     }
>     }

[names.preludes.no_implicit_prelude.syntax]

The `no_implicit_prelude` attribute uses the MetaWord syntax.

[names.preludes.no_implicit_prelude.allowed-positions]

The `no_implicit_prelude` attribute may only be applied to the crate or to a module.

> Note

> `rustc` ignores use in other positions but lints against it. This may become an error in the future.

[names.preludes.no_implicit_prelude.duplicates]

The `no_implicit_prelude` attribute may be used any number of times on a form.

> Note

> `rustc` lints against any use following the first.

[names.preludes.no_implicit_prelude.excluded-preludes]

The `no_implicit_prelude` attribute prevents the standard library prelude, extern prelude, `macro_use` prelude, and the tool prelude from being brought into scope for the module and its descendants.

[names.preludes.no_implicit_prelude.lang]

The `no_implicit_prelude` attribute does not affect the language prelude.

[names.preludes.no_implicit_prelude.edition2018]

> 2018 Edition differences

> In the 2015 edition, the `no_implicit_prelude` attribute does not affect the `macro_use` prelude, and all macros exported from the standard library are still included in the `macro_use` prelude. Starting in the 2018 edition, the attribute does remove the `macro_use` prelude.

[paths]

# Paths

[paths.intro]

A path is a sequence of one or more path segments separated by `::` tokens. Paths are used to refer to items, values, types, macros, and attributes.

Two examples of simple paths consisting of only identifier segments:

    x;
    x::y::z;

## Types of paths

[paths.simple]

### Simple paths

[paths.simple.syntax]

Syntax
SimplePath →
::? SimplePathSegment ( :: SimplePathSegment )*

SimplePathSegment →
IDENTIFIER | super | self | crate | $crate

[paths.simple.intro]

Simple paths are used in visibility markers, attributes, macros, and `use` items. For example:

    #![allow(unused)]
    fn main() {
    use std::io::{self, Write};
    mod m {
        #[clippy::cyclomatic_complexity = "0"]
        pub (in super) fn f1() {}
    }
    }

[paths.expr]

### Paths in expressions

[paths.expr.syntax]

Syntax
PathInExpression →
::? PathExprSegment ( :: PathExprSegment )*

PathExprSegment →
PathIdentSegment ( :: GenericArgs )?

PathIdentSegment →
IDENTIFIER | super | self | Self | crate | $crate

GenericArgs →
< >
| < ( GenericArg , )* GenericArg ,? >

GenericArg →
Lifetime | Type | GenericArgsConst | GenericArgsBinding | GenericArgsBounds

GenericArgsConst →
BlockExpression
| LiteralExpression
| - LiteralExpression
| SimplePathSegment

GenericArgsBinding →
IDENTIFIER GenericArgs? = Type

GenericArgsBounds →
IDENTIFIER GenericArgs? : TypeParamBounds

[paths.expr.intro]

Paths in expressions allow for paths with generic arguments to be specified. They are used in various places in expressions and patterns.

[paths.expr.turbofish]

The `::` token is required before the opening `<` for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as “turbofish” syntax.

    #![allow(unused)]
    fn main() {
    (0..10).collect::<Vec<_>>();
    Vec::<u8>::with_capacity(1024);
    }

[paths.expr.argument-order]

The order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints.

[paths.expr.complex-const-params]

Const arguments must be surrounded by braces unless they are a literal, an inferred const, or a single segment path. An inferred const may not be surrounded by braces.

    #![allow(unused)]
    fn main() {
    mod m {
        pub const C: usize = 1;
    }
    const C: usize = m::C;
    fn f<const N: usize>() -> [u8; N] { [0; N] }

    let _ = f::<1>(); // Literal.
    let _: [_; 1] = f::<_>(); // Inferred const.
    let _: [_; 1] = f::<(((_)))>(); // Inferred const.
    let _ = f::<C>(); // Single segment path.
    let _ = f::<{ m::C }>(); // Multi-segment path must be braced.
    }

    #![allow(unused)]
    fn main() {
    fn f<const N: usize>() -> [u8; N] { [0; _] }
    let _: [_; 1] = f::<{ _ }>();
    //                    ^ ERROR `_` not allowed here
    }

> Note

> In a generic argument list, an inferred const is parsed as an inferred type but then semantically treated as a separate kind of const generic argument.

[paths.expr.impl-trait-params]

The synthetic type parameters corresponding to `impl Trait` types are implicit, and these cannot be explicitly specified.

[paths.qualified]

## Qualified paths

[paths.qualified.syntax]

Syntax
QualifiedPathInExpression → QualifiedPathType ( :: PathExprSegment )+

QualifiedPathType → < Type ( as TypePath )? >

QualifiedPathInType → QualifiedPathType ( :: TypePathSegment )+

[paths.qualified.intro]

Fully qualified paths allow for disambiguating the path for trait implementations and for specifying canonical paths. When used in a type specification, it supports using the type syntax specified below.

    #![allow(unused)]
    fn main() {
    struct S;
    impl S {
        fn f() { println!("S"); }
    }
    trait T1 {
        fn f() { println!("T1 f"); }
    }
    impl T1 for S {}
    trait T2 {
        fn f() { println!("T2 f"); }
    }
    impl T2 for S {}
    S::f();  // Calls the inherent impl.
    <S as T1>::f();  // Calls the T1 trait function.
    <S as T2>::f();  // Calls the T2 trait function.
    }

[paths.type]

### Paths in types

[paths.type.syntax]

Syntax
TypePath → ::? TypePathSegment ( :: TypePathSegment )*

TypePathSegment → PathIdentSegment ( ::? ( GenericArgs | TypePathFn ) )?

TypePathFn → ( TypePathFnInputs? ) ( -> TypeNoBounds )?

TypePathFnInputs → Type ( , Type )* ,?

[paths.type.intro]

Type paths are used within type definitions, trait bounds, type parameter bounds, and qualified paths.

[paths.type.turbofish]

Although the `::` token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in PathInExpression.

    #![allow(unused)]
    fn main() {
    mod ops {
        pub struct Range<T> {f1: T}
        pub trait Index<T> {}
        pub struct Example<'a> {f1: &'a i32}
    }
    struct S;
    impl ops::Index<ops::Range<usize>> for S { /*...*/ }
    fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> {
        // ...
       const EXAMPLE: Vec<ops::Example<'static>> = Vec::new();
       EXAMPLE.into_iter()
    }
    type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>;
    }

[paths.qualifiers]

## Path qualifiers

Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved.

[paths.qualifiers.global-root]

### `::`

[paths.qualifiers.global-root.intro]

Paths starting with `::` are considered to be global paths where the segments of the path start being resolved from a place which differs based on edition. Each identifier in the path must resolve to an item.

[paths.qualifiers.global-root.edition2018]

> 2018 Edition differences

> In the 2015 Edition, identifiers resolve from the “crate root” (`crate::` in the 2018 edition), which contains a variety of different items, including external crates, default crates such as `std` or `core`, and items in the top level of the crate (including `use` imports).

> Beginning with the 2018 Edition, paths starting with `::` resolve from crates in the extern prelude. That is, they must be followed by the name of a crate.

    #![allow(unused)]
    fn main() {
    pub fn foo() {
        // In the 2018 edition, this accesses `std` via the extern prelude.
        // In the 2015 edition, this accesses `std` via the crate root.
        let now = ::std::time::Instant::now();
        println!("{:?}", now);
    }
    }

    // 2015 Edition
    mod a {
        pub fn foo() {}
    }
    mod b {
        pub fn foo() {
            ::a::foo(); // call `a`'s foo function
            // In Rust 2018, `::a` would be interpreted as the crate `a`.
        }
    }
    fn main() {}

[paths.qualifiers.mod-self]

### `self`

[paths.qualifiers.mod-self.intro]

`self` resolves the path relative to the current module.

[paths.qualifiers.mod-self.restriction]

`self` can only be used as the first segment, without a preceding `::`.

[paths.qualifiers.self-pat]

In a method body, a path which consists of a single `self` segment resolves to the method’s self parameter.

    fn foo() {}
    fn bar() {
        self::foo();
    }
    struct S(bool);
    impl S {
      fn baz(self) {
            self.0;
        }
    }
    fn main() {}

[paths.qualifiers.type-self]

### `Self`

[paths.qualifiers.type-self.intro]

`Self`, with a capital “S”, is used to refer to the current type being implemented or defined. It may be used in the following situations:

[paths.qualifiers.type-self.trait]

- In a trait definition, it refers to the type implementing the trait.

[paths.qualifiers.type-self.impl]

- In an implementation, it refers to the type being implemented. When implementing a tuple or unit struct, it also refers to the constructor in the value namespace.

[paths.qualifiers.type-self.type]

- In the definition of a struct, enumeration, or union, it refers to the type being defined. The definition is not allowed to be infinitely recursive (there must be an indirection).

[paths.qualifiers.type-self.scope]

The scope of `Self` behaves similarly to a generic parameter; see the `Self` scope section for more details.

[paths.qualifiers.type-self.allowed-positions]

`Self` can only be used as the first segment, without a preceding `::`.

[paths.qualifiers.type-self.no-generics]

The `Self` path cannot include generic arguments (as in `Self::<i32>`).

    #![allow(unused)]
    fn main() {
    trait T {
        type Item;
        const C: i32;
        // `Self` will be whatever type that implements `T`.
        fn new() -> Self;
        // `Self::Item` will be the type alias in the implementation.
        fn f(&self) -> Self::Item;
    }
    struct S;
    impl T for S {
        type Item = i32;
        const C: i32 = 9;
        fn new() -> Self {           // `Self` is the type `S`.
            S
        }
        fn f(&self) -> Self::Item {  // `Self::Item` is the type `i32`.
            Self::C                  // `Self::C` is the constant value `9`.
        }
    }

    // `Self` is in scope within the generics of a trait definition,
    // to refer to the type being defined.
    trait Add<Rhs = Self> {
        type Output;
        // `Self` can also reference associated items of the
        // type being implemented.
        fn add(self, rhs: Rhs) -> Self::Output;
    }

    struct NonEmptyList<T> {
        head: T,
        // A struct can reference itself (as long as it is not
        // infinitely recursive).
        tail: Option<Box<Self>>,
    }
    }

[paths.qualifiers.super]

### `super`

[paths.qualifiers.super.intro]

`super` in a path resolves to the parent module.

[paths.qualifiers.super.allowed-positions]

It may only be used in leading segments of the path, possibly after an initial `self` segment.

    mod a {
        pub fn foo() {}
    }
    mod b {
        pub fn foo() {
            super::a::foo(); // call a's foo function
        }
    }
    fn main() {}

[paths.qualifiers.super.repetition]

`super` may be repeated several times after the first `super` or `self` to refer to ancestor modules.

    mod a {
        fn foo() {}

        mod b {
            mod c {
                fn foo() {
                    super::super::foo(); // call a's foo function
                    self::super::super::foo(); // call a's foo function
                }
            }
        }
    }
    fn main() {}

[paths.qualifiers.crate]

### `crate`

[paths.qualifiers.crate.intro]

`crate` resolves the path relative to the current crate.

[paths.qualifiers.crate.allowed-positions]

`crate` can only be used as the first segment, without a preceding `::`.

    fn foo() {}
    mod a {
        fn bar() {
            crate::foo();
        }
    }
    fn main() {}

[paths.qualifiers.macro-crate]

### `$crate`

[paths.qualifiers.macro-crate.allowed-positions]

`$crate` is only used within macro transcribers, and can only be used as the first segment, without a preceding `::`.

[paths.qualifiers.macro-crate.hygiene]

`$crate` will expand to a path to access items from the top level of the crate where the macro is defined, regardless of which crate the macro is invoked.

    pub fn increment(x: u32) -> u32 {
        x + 1
    }

    #[macro_export]
    macro_rules! inc {
        ($x:expr) => ( $crate::increment($x) )
    }
    fn main() { }

[paths.canonical]

## Canonical paths

[paths.canonical.intro]

Items defined in a module or implementation have a canonical path that corresponds to where within its crate it is defined.

[paths.canonical.alias]

All other paths to these items are aliases.

[paths.canonical.def]

The canonical path is defined as a path prefix appended by the path segment the item itself defines.

[paths.canonical.non-canonical]

Implementations and use declarations do not have canonical paths, although the items that implementations define do have them. Items defined in block expressions do not have canonical paths. Items defined in a module that does not have a canonical path do not have a canonical path. Associated items defined in an implementation that refers to an item without a canonical path, e.g. as the implementing type, the trait being implemented, a type parameter or bound on a type parameter, do not have canonical paths.

[paths.canonical.module-prefix]

The path prefix for modules is the canonical path to that module.

[paths.canonical.bare-impl-prefix]

For bare implementations, it is the canonical path of the item being implemented surrounded by angle (`<>`) brackets.

[paths.canonical.trait-impl-prefix]

For trait implementations, it is the canonical path of the item being implemented followed by `as` followed by the canonical path to the trait all surrounded in angle (`<>`) brackets.

[paths.canonical.local-canonical-path]

The canonical path is only meaningful within a given crate. There is no global namespace across crates; an item’s canonical path merely identifies it within the crate.

    // Comments show the canonical path of the item.

    mod a { // crate::a
        pub struct Struct; // crate::a::Struct

        pub trait Trait { // crate::a::Trait
            fn f(&self); // crate::a::Trait::f
        }

        impl Trait for Struct {
            fn f(&self) {} // <crate::a::Struct as crate::a::Trait>::f
        }

        impl Struct {
            fn g(&self) {} // <crate::a::Struct>::g
        }
    }

    mod without { // crate::without
        fn canonicals() { // crate::without::canonicals
            struct OtherStruct; // None

            trait OtherTrait { // None
                fn g(&self); // None
            }

            impl OtherTrait for OtherStruct {
                fn g(&self) {} // None
            }

            impl OtherTrait for crate::a::Struct {
                fn g(&self) {} // None
            }

            impl crate::a::Trait for OtherStruct {
                fn f(&self) {} // None
            }
        }
    }

    fn main() {}

[names.resolution]

# Name resolution

[names.resolution.intro]

Name resolution is the process of tying paths and other identifiers to the declarations of those entities. Names are segregated into different namespaces, allowing entities in different namespaces to share the same name without conflict. Each name is valid within a scope, or a region of source text where that name may be referenced. Access to a name may be restricted based on its visibility.

Name resolution is split into three stages throughout the compilation process. The first stage, expansion-time resolution, resolves all `use` declarations and macro invocations. The second stage, primary resolution, resolves all names that have not yet been resolved and that do not depend on type information to resolve. The last stage, type-relative resolution, resolves the remaining names once type information is available.

> Note

> Expansion-time resolution is also known as early resolution. Primary resolution is also known as late resolution.

[names.resolution.general]

## General

[names.resolution.general.intro]

The rules within this section apply to all stages of name resolution.

[names.resolution.general.scopes]

### Scopes

[names.resolution.general.scopes.intro]

> Note

> This is a placeholder for future expansion about resolution of names within various scopes.

[names.resolution.expansion]

## Expansion-time name resolution

[names.resolution.expansion.intro]

Expansion-time name resolution is the stage of name resolution necessary to complete macro expansion and fully generate a crate’s AST. This stage requires the resolution of macro invocations and `use` declarations. Resolving `use` declarations is required for macro invocations that resolve via path-based scope. Resolving macro invocations is required in order to expand them.

[names.resolution.expansion.unresolved-invocations]

After expansion-time name resolution, the AST must not contain any unexpanded macro invocations. Every macro invocation resolves to a valid definition that exists in the final AST or in an external crate.

    #![allow(unused)]
    fn main() {
    m!(); // ERROR: Cannot find macro `m` in this scope.
    }

[names.resolution.expansion.expansion-order-stability]

The resolution of names must be stable. After expansion, names in the fully expanded AST must resolve to the same definition regardless of the order in which macros are expanded and imports are resolved.

[names.resolution.expansion.speculation]

All name resolution candidates selected during macro expansion are considered speculative. Once the crate has been fully expanded, all speculative import resolutions are validated to ensure that macro expansion did not introduce any new ambiguities.

> Note

> Due to the iterative nature of macro expansion, this causes so-called time traveling ambiguities, such as when a macro or glob import introduces an item that is ambiguous with its own base path.

>     fn main() {}
>     macro_rules! f {
>         () => {
>             mod m {
>                 pub(crate) use f;
>             }
>         }
>     }
>     f!();

>     const _: () = {
>         // Initially, we speculatively resolve `m` to the module in
>         // the crate root.
>         //
>         // Expansion of `f` introduces a second `m` module inside this
>         // body.
>         //
>         // Expansion-time resolution finalizes resolutions by re-
>         // resolving all imports and macro invocations, sees the
>         // introduced ambiguity and reports it as an error.
>         m::f!(); // ERROR: `m` is ambiguous.
>     };

[names.resolution.expansion.imports]

### Imports

[names.resolution.expansion.imports.intro]

All `use` declarations are fully resolved during this stage of resolution. Type-relative paths cannot be resolved at this stage and will produce an error.

    #![allow(unused)]
    fn main() {
    mod m {
        pub const C: () = ();
        pub enum E { V }
        pub type A = E;
        impl E {
            pub const C: () = ();
        }
    }

    // Valid imports resolved at expansion-time:
    use m::C; // OK.
    use m::E; // OK.
    use m::A; // OK.
    use m::E::V; // OK.

    // Valid expressions resolved during type-relative resolution:
    let _ = m::A::V; // OK.
    let _ = m::E::C; // OK.
    }

    #![allow(unused)]
    fn main() {
    mod m {
        pub const C: () = ();
        pub enum E { V }
        pub type A = E;
        impl E {
            pub const C: () = ();
        }
    }
    // Invalid type-relative imports that can't resolve at expansion-time:
    use m::A::V; // ERROR: Unresolved import `m::A::V`.
    use m::E::C; // ERROR: Unresolved import `m::E::C`.
    }

[names.resolution.expansion.imports.shadowing]

Names introduced via `use` declarations in an outer scope are shadowed by candidates in the same namespace with the same name from an inner scope except where otherwise restricted by name resolution ambiguities.

    #![allow(unused)]
    fn main() {
    pub mod m1 {
        pub mod ambig {
            pub const C: u8 = 1;
        }
    }

    pub mod m2 {
        pub mod ambig {
            pub const C: u8 = 2;
        }
    }

    // This introduces the name `ambig` in the outer scope.
    use m1::ambig;
    const _: () = {
        // This shadows `ambig` in the inner scope.
        use m2::ambig;
        // The inner candidate is selected here
        // as the resolution of `ambig`.
        use ambig::C;
        assert!(C == 2);
    };
    }

[names.resolution.expansion.imports.shadowing.shared-scope]

Shadowing of names introduced via `use` declarations within a single scope is permitted in the following situations:

- `use` glob shadowing
- Macro textual scope shadowing

[names.resolution.expansion.imports.ambiguity]

#### Ambiguities

[names.resolution.expansion.imports.ambiguity.intro]

There are certain situations during expansion-time resolution where there are multiple macro definitions, `use` declarations, or modules an import or macro invocation’s name could refer to where the compiler cannot consistently determine which candidate should shadow the other. Shadowing cannot be permitted in these situations and the compiler instead emits ambiguity errors.

[names.resolution.expansion.imports.ambiguity.glob-vs-glob]

Names may not be resolved through ambiguous glob imports. Glob imports are allowed to import conflicting names in the same namespace as long as the name is not used. Names with conflicting candidates from ambiguous glob imports may still be shadowed by non-glob imports and used without producing an error. The errors occur at time of use, not time of import.

    #![allow(unused)]
    fn main() {
    mod m1 {
        pub struct Ambig;
    }

    mod m2 {
        pub struct Ambig;
    }

    // OK: This brings conficting names in the same namespace into scope
    // but they have not been used yet.
    use m1::*;
    use m2::*;

    const _: () = {
        // The error happens when the name with the conflicting candidates
        // is used.
        let x = Ambig; // ERROR: `Ambig` is ambiguous.
    }
    }

    #![allow(unused)]
    fn main() {
    mod m1 {
        pub struct Ambig;
    }

    mod m2 {
        pub struct Ambig;
    }

    use m1::*;
    use m2::*; // OK: No name conflict.
    const _: () = {
        // This is permitted, since resolution is not through the
        // ambiguous globs.
        struct Ambig;
        let x = Ambig; // OK.
    };
    }

Multiple glob imports are allowed to import the same name, and that name is allowed to be used if the imports are of the same item (following reexports). The visibility of the name is the maximum visibility of the imports.

    mod m1 {
        pub struct Ambig;
    }

    mod m2 {
        // This reexports the same `Ambig` item from a second module.
        pub use super::m1::Ambig;
    }

    mod m3 {
        // These both import the same `Ambig`.
        //
        // The visibility of `Ambig` is `pub` because that is the
        // maximum visibility between these two `use` declarations.
        pub use super::m1::*;
        use super::m2::*;
    }

    mod m4 {
        // `Ambig` can be used through the `m3` globs and still has
        // `pub` visibility.
        pub use crate::m3::Ambig;
    }

    const _: () = {
        // Therefore, we can use it here.
        let _ = m4::Ambig; // OK.
    };
    fn main() {}

[names.resolution.expansion.imports.ambiguity.glob-vs-outer]

Names in imports and macro invocations may not be resolved through glob imports when there is another candidate available in an outer scope.

    #![allow(unused)]
    fn main() {
    mod glob {
        pub mod ambig {
            pub struct Name;
        }
    }

    // Outer `ambig` candidate.
    pub mod ambig {
        pub struct Name;
    }

    const _: () = {
        // Cannot resolve `ambig` through this glob
        // because of the outer `ambig` candidate above.
        use glob::*;
        use ambig::Name; // ERROR: `ambig` is ambiguous.
    };
    }

    #![allow(unused)]
    fn main() {
    // As above, but with macros.
    pub mod m {
        macro_rules! f {
            () => {};
        }
        pub(crate) use f;
    }
    pub mod glob {
        macro_rules! f {
            () => {};
        }
        pub(crate) use f as ambig;
    }

    use m::f as ambig;

    const _: () = {
        use glob::*;
        ambig!(); // ERROR: `ambig` is ambiguous.
    };
    }

> Note

> These ambiguity errors are specific to expansion-time resolution. Having multiple candidates available for a given name during later stages of resolution is not considered an error. So long as none of the imports themselves are ambiguous, there will always be a single unambiguous closest resolution.

>     #![allow(unused)]
>     fn main() {
>     mod glob {
>         pub const AMBIG: u8 = 1;
>     }

>     mod outer {
>         pub const AMBIG: u8 = 2;
>     }

>     use outer::AMBIG;

>     const C: () = {
>         use glob::*;
>         assert!(AMBIG == 1);
>         //      ^---- This `AMBIG` is resolved during primary resolution.
>     };
>     }

[names.resolution.expansion.imports.ambiguity.path-vs-textual-macro]

Names may not be resolved through ambiguous macro reexports. Macro reexports are ambiguous when they would shadow a textual macro candidate for the same name in an outer scope.

    #![allow(unused)]
    fn main() {
    // Textual macro candidate.
    macro_rules! ambig {
        () => {}
    }

    // Path-based macro candidate.
    macro_rules! path_based {
        () => {}
    }

    pub fn f() {
        // This reexport of the `path_based` macro definition
        // as `ambig` may not shadow the `ambig` macro definition
        // which is resolved via textual macro scope.
        use path_based as ambig;
        ambig!(); // ERROR: `ambig` is ambiguous.
    }
    }

> Note

> This restriction is needed due to implementation details in the compiler, specifically the current scope visitation logic and the complexity of supporting this behavior. This ambiguity error may be removed in the future.

[names.resolution.expansion.macros]

### Macros

[names.resolution.expansion.macros.intro]

Macros are resolved by iterating through the available scopes to find the available candidates. Macros are split into two sub-namespaces, one for function-like macros, and the other for attributes and derives. Resolution candidates from the incorrect sub-namespace are ignored.

[names.resolution.expansion.macros.visitation-order]

The available scope kinds are visited in the following order. Each of these scope kinds represent one or more scopes.

- Derive helpers
- Textual scope macros
- Path-based scope macros
- `macro_use` prelude
- Standard library prelude
- Builtin attributes

> Note

> The compiler will attempt to resolve derive helpers that are used before their associated macro introduces them into scope. This scope is visited after the scope for resolving derive helper candidates that are correctly in scope. This behavior is slated for removal.

> For more info see derive helper scope.

> Note

> This visitation order may change in the future, such as interleaving the visitation of textual and path-based scope candidates based on their lexical scopes.

> 2018 Edition differences

> Starting in edition 2018 the `#[macro_use]` prelude is not visited when `#[no_implicit_prelude]` is present.

[names.resolution.expansion.macros.reserved-names]

The names `cfg` and `cfg_attr` are reserved in the macro attribute sub-namespace.

[names.resolution.expansion.macros.ambiguity]

#### Ambiguities

[names.resolution.expansion.macros.ambiguity.more-expanded-vs-outer]

Names may not be resolved through ambiguous candidates inside of macro expansions. Candidates inside of macro expansions are ambiguous when they would shadow a candidate for the same name from outside of the first candidate’s macro expansion and the invocation of the name being resolved is also from outside of the first candidate’s macro expansion.

    #![allow(unused)]
    fn main() {
    macro_rules! define_ambig {
        () => {
            macro_rules! ambig {
                () => {}
            }
        }
    }

    // Introduce outer candidate definition for `ambig` macro invocation.
    macro_rules! ambig {
        () => {}
    }

    // Introduce a second candidate definition for `ambig` inside of a
    // macro expansion.
    define_ambig!();

    // The definition of `ambig` from the second invocation
    // of `define_ambig` is the innermost canadidate.
    //
    // The definition of `ambig` from the first invocation of
    // `define_ambig` is the second candidate.
    //
    // The compiler checks that the first candidate is inside of a macro
    // expansion, that the second candidate is not from within the same
    // macro expansion, and that the name being resolved is not from
    // within the same macro expansion.
    ambig!(); // ERROR: `ambig` is ambiguous.
    }

The reverse is not considered ambiguous.

    #![allow(unused)]
    fn main() {
    macro_rules! define_ambig {
        () => {
            macro_rules! ambig {
                () => {}
            }
        }
    }
    // Swap order of definitions.
    define_ambig!();
    macro_rules! ambig {
        () => {}
    }
    // The innermost candidate is now less expanded so it may shadow more
    // the macro expanded definition above it.
    ambig!();
    }

Nor is it ambiguous if the invocation being resolved is within the innermost candidate’s expansion.

    #![allow(unused)]
    fn main() {
    macro_rules! ambig {
        () => {}
    }

    macro_rules! define_and_invoke_ambig {
        () => {
            // Define innermost candidate.
            macro_rules! ambig {
                () => {}
            }

            // Invocation of `ambig` is in the same expansion as the
            // innermost candidate.
            ambig!(); // OK
        }
    }

    define_and_invoke_ambig!();
    }

It doesn’t matter if both definitions come from invocations of the same macro; the outermost candidate is still considered “less expanded” because it is not within the expansion containing the innermost candidate’s definition.

    #![allow(unused)]
    fn main() {
    macro_rules! define_ambig {
        () => {
            macro_rules! ambig {
                () => {}
            }
        }
    }
    define_ambig!();
    define_ambig!();
    ambig!(); // ERROR: `ambig` is ambiguous.
    }

This also applies to imports so long as the innermost candidate for the name is from within a macro expansion.

    #![allow(unused)]
    fn main() {
    macro_rules! define_ambig {
        () => {
            mod ambig {
                pub struct Name;
            }
        }
    }

    mod ambig {
        pub struct Name;
    }

    const _: () = {
        // Introduce innermost candidate for
        // `ambig` mod in this macro expansion.
        define_ambig!();
        use ambig::Name; // ERROR: `ambig` is ambiguous.
    };
    }

[names.resolution.expansion.macros.ambiguity.built-in-attr]

User-defined attributes or derive macros may not shadow built-in non-macro attributes (e.g. inline).

    // with-helper/src/lib.rs
    use proc_macro::TokenStream;
    #[proc_macro_derive(WithHelperAttr, attributes(non_exhaustive))]
    //                                             ^^^^^^^^^^^^^^
    //                                   User-defined attribute candidate.
    // ...
    pub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream {
        TokenStream::new()
    }

    // src/lib.rs
    #[derive(with_helper::WithHelperAttr)]
    #[non_exhaustive] // ERROR: `non_exhaustive` is ambiguous.
    struct S;

> Note

> This applies regardless of the name the built-in attribute is a candidate for:

>     // with-helper/src/lib.rs
>     use proc_macro::TokenStream;

>     #[proc_macro_derive(WithHelperAttr, attributes(helper))]
>     //                                             ^^^^^^
>     //                                 User-defined attribute candidate.
>     // ...
>     pub fn derive_with_helper_attr(_item: TokenStream) -> TokenStream {
>         TokenStream::new()
>     }

>     // src/lib.rs
>     use inline as helper;
>     //            ^----- Built-in attribute candidate via reexport.

>     #[derive(with_helper::WithHelperAttr)]
>     #[helper] // ERROR: `helper` is ambiguous.
>     struct S;

[names.resolution.primary]

## Primary name resolution

> Note

> This is a placeholder for future expansion about primary name resolution.

[names.resolution.type-relative]

## Type-relative resolution

> Note

> This is a placeholder for future expansion about type-dependent resolution.

[vis]

# Visibility and privacy

[vis.syntax]

Syntax
Visibility →
pub
| pub ( crate )
| pub ( self )
| pub ( super )
| pub ( in SimplePath )

[vis.intro]

These two terms are often used interchangeably, and what they are attempting to convey is the answer to the question “Can this item be used at this location?”

[vis.name-hierarchy]

Rust’s name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition.

[vis.privacy]

To control whether interfaces can be used across modules, Rust checks each use of an item to see whether it should be allowed or not. This is where privacy warnings are generated, or otherwise “you used a private item of another module and weren’t allowed to.”

[vis.default]

By default, everything is private, with two exceptions: Associated items in a `pub` Trait are public by default; Enum variants in a `pub` enum are also public by default. When an item is declared as `pub`, it can be thought of as being accessible to the outside world. For example:

    fn main() {}
    // Declare a private struct
    struct Foo;

    // Declare a public struct with a private field
    pub struct Bar {
        field: i32,
    }

    // Declare a public enum with two public variants
    pub enum State {
        PubliclyAccessibleState,
        PubliclyAccessibleState2,
    }

[vis.access]

With the notion of an item being either public or private, Rust allows item accesses in two cases:

1. If an item is public, then it can be accessed externally from some module `m` if you can access all the item’s ancestor modules from `m`. You can also potentially be able to name the item through re-exports. See below.
2. If an item is private, it may be accessed by the current module and its descendants.

These two cases are surprisingly powerful for creating module hierarchies exposing public APIs while hiding internal implementation details. To help explain, here’s a few use cases and what they would entail:

- A library developer needs to expose functionality to crates which link against their library. As a consequence of the first case, this means that anything which is usable externally must be `pub` from the root down to the destination item. Any private item in the chain will disallow external accesses.

- A crate needs a global available “helper module” to itself, but it doesn’t want to expose the helper module as a public API. To accomplish this, the root of the crate’s hierarchy would have a private module which then internally has a “public API”. Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case.

- When writing unit tests for a module, it’s often a common idiom to have an immediate child of the module to-be-tested named `mod test`. This module could access any items of the parent module through the second case, meaning that internal implementation details could also be seamlessly tested from the child module.

In the second case, it mentions that a private item “can be accessed” by the current module and its descendants, but the exact meaning of accessing an item depends on what the item is.

[vis.usage]

Accessing a module, for example, would mean looking inside of it (to import more items). On the other hand, accessing a function would mean that it is invoked. Additionally, path expressions and import statements are considered to access an item in the sense that the import/expression is only valid if the destination is in the current visibility scope.

Here’s an example of a program which exemplifies the three cases outlined above:

    // This module is private, meaning that no external crate can access this
    // module. Because it is private at the root of this current crate, however, any
    // module in the crate may access any publicly visible item in this module.
    mod crate_helper_module {

        // This function can be used by anything in the current crate
        pub fn crate_helper() {}

        // This function *cannot* be used by anything else in the crate. It is not
        // publicly visible outside of the `crate_helper_module`, so only this
        // current module and its descendants may access it.
        fn implementation_detail() {}
    }

    // This function is "public to the root" meaning that it's available to external
    // crates linking against this one.
    pub fn public_api() {}

    // Similarly to 'public_api', this module is public so external crates may look
    // inside of it.
    pub mod submodule {
        use crate::crate_helper_module;

        pub fn my_method() {
            // Any item in the local crate may invoke the helper module's public
            // interface through a combination of the two rules above.
            crate_helper_module::crate_helper();
        }

        // This function is hidden to any module which is not a descendant of
        // `submodule`
        fn my_implementation() {}

        #[cfg(test)]
        mod test {

            #[test]
            fn test_my_implementation() {
                // Because this module is a descendant of `submodule`, it's allowed
                // to access private items inside of `submodule` without a privacy
                // violation.
                super::my_implementation();
            }
        }
    }

    fn main() {}

For a Rust program to pass the privacy checking pass, all paths must be valid accesses given the two rules above. This includes all use statements, expressions, types, etc.

[vis.scoped]

## `pub(in path)`, `pub(crate)`, `pub(super)`, and `pub(self)`

[vis.scoped.intro]

In addition to public and private, Rust allows users to declare an item as visible only within a given scope. The rules for `pub` restrictions are as follows:

[vis.scoped.in]

- `pub(in path)` makes an item visible within the provided `path`. `path` must be a simple path which resolves to an ancestor module of the item whose visibility is being declared. Each identifier in `path` must refer directly to a module (not to a name introduced by a `use` statement).

[vis.scoped.crate]

- `pub(crate)` makes an item visible within the current crate.

[vis.scoped.super]

- `pub(super)` makes an item visible to the parent module. This is equivalent to `pub(in super)`.

[vis.scoped.self]

- `pub(self)` makes an item visible to the current module. This is equivalent to `pub(in self)` or not using `pub` at all.

[vis.scoped.edition2018]

> 2018 Edition differences

> Starting with the 2018 edition, paths for `pub(in path)` must start with `crate`, `self`, or `super`. The 2015 edition may also use paths starting with `::` or modules from the crate root.

Here’s an example:

    pub mod outer_mod {
        pub mod inner_mod {
            // This function is visible within `outer_mod`
            pub(in crate::outer_mod) fn outer_mod_visible_fn() {}
            // Same as above, this is only valid in the 2015 edition.
            pub(in outer_mod) fn outer_mod_visible_fn_2015() {}

            // This function is visible to the entire crate
            pub(crate) fn crate_visible_fn() {}

            // This function is visible within `outer_mod`
            pub(super) fn super_mod_visible_fn() {
                // This function is visible since we're in the same `mod`
                inner_mod_visible_fn();
            }

            // This function is visible only within `inner_mod`,
            // which is the same as leaving it private.
            pub(self) fn inner_mod_visible_fn() {}
        }
        pub fn foo() {
            inner_mod::outer_mod_visible_fn();
            inner_mod::crate_visible_fn();
            inner_mod::super_mod_visible_fn();

            // This function is no longer visible since we're outside of `inner_mod`
            // Error! `inner_mod_visible_fn` is private
            //inner_mod::inner_mod_visible_fn();
        }
    }

    fn bar() {
        // This function is still visible since we're in the same crate
        outer_mod::inner_mod::crate_visible_fn();

        // This function is no longer visible since we're outside of `outer_mod`
        // Error! `super_mod_visible_fn` is private
        //outer_mod::inner_mod::super_mod_visible_fn();

        // This function is no longer visible since we're outside of `outer_mod`
        // Error! `outer_mod_visible_fn` is private
        //outer_mod::inner_mod::outer_mod_visible_fn();

        outer_mod::foo();
    }

    fn main() { bar() }

> Note

> This syntax only adds another restriction to the visibility of an item. It does not guarantee that the item is visible within all parts of the specified scope. To access an item, all of its parent items up to the current scope must still be visible as well.

[vis.reexports]

## Re-exporting and visibility

[vis.reexports.intro]

Rust allows publicly re-exporting items through a `pub use` directive. Because this is a public directive, this allows the item to be used in the current module through the rules above. It essentially allows public access into the re-exported item. For example, this program is valid:

    pub use self::implementation::api;

    mod implementation {
        pub mod api {
            pub fn f() {}
        }
    }

    fn main() {}

This means that any external crate referencing `implementation::api::f` would receive a privacy violation, while the path `api::f` would be allowed.

[vis.reexports.private-item]

When re-exporting a private item, it can be thought of as allowing the “privacy chain” being short-circuited through the reexport instead of passing through the namespace hierarchy as it normally would.

[memory]

# Memory model

> Warning

> The memory model of Rust is incomplete and not fully decided.

[memory.bytes]

## Bytes

[memory.bytes.intro]

The most basic unit of memory in Rust is a byte.

> Note

> While bytes are typically lowered to hardware bytes, Rust uses an “abstract” notion of bytes that can make distinctions which are absent in hardware, such as being uninitialized, or storing part of a pointer. Those distinctions can affect whether your program has undefined behavior, so they still have tangible impact on how compiled Rust programs behave.

[memory.bytes.contents]

Each byte may have one of the following values:

[memory.bytes.init]

- An initialized byte containing a `u8` value and optional provenance,

[memory.bytes.uninit]

- An uninitialized byte.

> Note

> The above list is not yet guaranteed to be exhaustive.

[alloc]

# Memory allocation and lifetime

[alloc.static]

The items of a program are those functions, modules, and types that have their value calculated at compile-time and stored uniquely in the memory image of the rust process. Items are neither dynamically allocated nor freed.

[alloc.dynamic]

The heap is a general term that describes boxes. The lifetime of an allocation in the heap depends on the lifetime of the box values pointing to it. Since box values may themselves be passed in and out of frames, or stored in the heap, heap allocations may outlive the frame they are allocated within. An allocation in the heap is guaranteed to reside at a single location in the heap for the whole lifetime of the allocation - it will never be relocated as a result of moving a box value.

[variable]

# Variables

[variable.intro]

A variable is a component of a stack frame, either a named function parameter, an anonymous temporary, or a named local variable.

[variable.local]

A local variable (or stack-local allocation) holds a value directly, allocated within the stack’s memory. The value is a part of the stack frame.

[variable.local-mut]

Local variables are immutable unless declared otherwise. For example: `let mut x = ...`.

[variable.param-mut]

Function parameters are immutable unless declared with `mut`. The `mut` keyword applies only to the following parameter. For example: `|mut x, y|` and `fn f(mut x: Box<i32>, y: Box<i32>)` declare one mutable variable `x` and one immutable variable `y`.

[variable.init]

Local variables are not initialized when allocated. Instead, the entire frame worth of local variables are allocated, on frame-entry, in an uninitialized state. Subsequent statements within a function may or may not initialize the local variables. Local variables can be used only after they have been initialized through all reachable control flow paths.

In this next example, `init_after_if` is initialized after the `if` expression while `uninit_after_if` is not because it is not initialized in the `else` case.

    #![allow(unused)]
    fn main() {
    fn random_bool() -> bool { true }
    fn initialization_example() {
        let init_after_if: ();
        let uninit_after_if: ();

        if random_bool() {
            init_after_if = ();
            uninit_after_if = ();
        } else {
            init_after_if = ();
        }

        init_after_if; // ok
        // uninit_after_if; // err: use of possibly uninitialized `uninit_after_if`
    }
    }

[panic]

# Panic

[panic.intro]

Rust provides a mechanism to prevent a function from returning normally, and instead “panic,” which is a response to an error condition that is typically not expected to be recoverable within the context in which the error is encountered.

[panic.lang-ops]

Some language constructs, such as out-of-bounds array indexing, panic automatically.

[panic.control]

There are also language features that provide a level of control over panic behavior:

- A panic handler defines the behavior of a panic.
- FFI ABIs may alter how panics behave.

> Note

> The standard library provides the capability to explicitly panic via the `panic!` macro.

[panic.panic_handler]

## The `panic_handler` attribute

[panic.panic_handler.intro]

The `panic_handler` attribute can be applied to a function to define the behavior of panics.

[panic.panic_handler.allowed-positions]

The `panic_handler` attribute can only be applied to a function with signature `fn(&PanicInfo) -> !`.

> Note

> The `PanicInfo` struct contains information about the location of the panic.

[panic.panic_handler.unique]

There must be a single `panic_handler` function in the dependency graph.

Below is shown a `panic_handler` function that logs the panic message and then halts the thread.

    #![no_std]

    use core::fmt::{self, Write};
    use core::panic::PanicInfo;

    struct Sink {
        // ..
       _0: (),
    }

    impl Sink {
        fn new() -> Sink { Sink { _0: () }}
    }

    impl fmt::Write for Sink {
        fn write_str(&mut self, _: &str) -> fmt::Result { Ok(()) }
    }

    #[panic_handler]
    fn panic(info: &PanicInfo) -> ! {
        let mut sink = Sink::new();

        // logs "panicked at '$reason', src/main.rs:27:4" to some `sink`
        let _ = writeln!(sink, "{}", info);

        loop {}
    }

[panic.panic_handler.std]

### Standard behavior

[panic.panic_handler.std.kinds]

`std` provides two different panic handlers:

- `unwind` — unwinds the stack and is potentially recoverable.
- `abort` –– aborts the process and is non-recoverable.

Not all targets may provide the `unwind` handler.

> Note

> The panic handler used when linking with `std` can be set with the `-C panic` CLI flag. The default for most targets is `unwind`.

> The standard library’s panic behavior can be modified at runtime with the `std::panic::set_hook` function.

[panic.panic_handler.std.no_std]

Linking a `no_std` binary, dylib, cdylib, or staticlib will require specifying your own panic handler.

[panic.strategy]

## Panic strategy

[panic.strategy.intro]

The panic strategy defines the kind of panic behavior that a crate is built to support.

> Note

> The panic strategy can be chosen in `rustc` with the `-C panic` CLI flag.

> When generating a binary, dylib, cdylib, or staticlib and linking with `std`, the `-C panic` CLI flag also influences which panic handler is used.

> Note

> When compiling code with the `abort` panic strategy, the optimizer may assume that unwinding across Rust frames is impossible, which can result in both code-size and runtime speed improvements.

> Note

> See link.unwinding for restrictions on linking crates with different panic strategies. An implication is that crates built with the `unwind` strategy can use the `abort` panic handler, but the `abort` strategy cannot use the `unwind` panic handler.

[panic.unwind]

## Unwinding

[panic.unwind.intro]

Panicking may either be recoverable or non-recoverable, though it can be configured (by choosing a non-unwinding panic handler) to always be non-recoverable. (The converse is not true: the `unwind` handler does not guarantee that all panics are recoverable, only that panicking via the `panic!` macro and similar standard library mechanisms is recoverable.)

[panic.unwind.destruction]

When a panic occurs, the `unwind` handler “unwinds” Rust frames, just as C++’s `throw` unwinds C++ frames, until the panic reaches the point of recovery (for instance at a thread boundary). This means that as the panic traverses Rust frames, live objects in those frames that implement `Drop` will have their `drop` methods called. Thus, when normal execution resumes, no-longer-accessible objects will have been “cleaned up” just as if they had gone out of scope normally.

> Note

> As long as this guarantee of resource-cleanup is preserved, “unwinding” may be implemented without actually using the mechanism used by C++ for the target platform.

> Note

> The standard library provides two mechanisms for recovering from a panic, `std::panic::catch_unwind` (which enables recovery within the panicking thread) and `std::thread::spawn` (which automatically sets up panic recovery for the spawned thread so that other threads may continue running).

[panic.unwind.ffi]

### Unwinding across FFI boundaries

[panic.unwind.ffi.intro]

It is possible to unwind across FFI boundaries using an appropriate ABI declaration. While useful in certain cases, this creates unique opportunities for undefined behavior, especially when multiple language runtimes are involved.

[panic.unwind.ffi.undefined]

Unwinding with the wrong ABI is undefined behavior:

- Causing an unwind into Rust code from a foreign function that was called via a function declaration or pointer declared with a non-unwinding ABI, such as `"C"`, `"system"`, etc. (For example, this case occurs when such a function written in C++ throws an exception that is uncaught and propagates to Rust.)
- Calling a Rust `extern` function that unwinds (with `extern "C-unwind"` or another ABI that permits unwinding) from code that does not support unwinding, such as code compiled with GCC or Clang using `-fno-exceptions`

[panic.unwind.ffi.catch-foreign]

Catching a foreign unwinding operation (such as a C++ exception) using `std::panic::catch_unwind`, `std::thread::JoinHandle::join`, or by letting it propagate beyond the Rust `main()` function or thread root will have one of two behaviors, and it is unspecified which will occur:

- The process aborts.
- The function returns a `Result::Err` containing an opaque type.

> Note

> Rust code compiled or linked with a different instance of the Rust standard library counts as a “foreign exception” for the purpose of this guarantee. Thus, a library that uses `panic!` and is linked against one version of the Rust standard library, invoked from an application that uses a different version of the standard library, may cause the entire application to abort even if the library is only used within a child thread.

[panic.unwind.ffi.dispose-panic]

There are currently no guarantees about the behavior that occurs when a foreign runtime attempts to dispose of, or rethrow, a Rust `panic` payload. In other words, an unwind originated from a Rust runtime must either lead to termination of the process or be caught by the same runtime.

[link]

# Linkage

> Note

> This section is described more in terms of the compiler than of the language.

[link.intro]

The compiler supports various methods to link crates together both statically and dynamically. This section will explore the various methods to link crates together, and more information about native libraries can be found in the FFI section of the book.

[link.type]

In one session of compilation, the compiler can generate multiple artifacts through the usage of either command line flags or the `crate_type` attribute. If one or more command line flags are specified, all `crate_type` attributes will be ignored in favor of only building the artifacts specified by command line.

[link.bin]

- `--crate-type=bin`, `#![crate_type = "bin"]` - A runnable executable will be produced. This requires that there is a `main` function in the crate which will be run when the program begins executing. This will link in all Rust and native dependencies, producing a single distributable binary. This is the default crate type.

[link.lib]

- `--crate-type=lib`, `#![crate_type = "lib"]` - A Rust library will be produced. This is an ambiguous concept as to what exactly is produced because a library can manifest itself in several forms. The purpose of this generic `lib` option is to generate the “compiler recommended” style of library. The output library will always be usable by rustc, but the actual type of library may change from time-to-time. The remaining output types are all different flavors of libraries, and the `lib` type can be seen as an alias for one of them (but the actual one is compiler-defined).

[link.dylib]

- `--crate-type=dylib`, `#![crate_type = "dylib"]` - A dynamic Rust library will be produced. This is different from the `lib` output type in that this forces dynamic library generation. The resulting dynamic library can be used as a dependency for other libraries and/or executables. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows.

[link.staticlib]

- `--crate-type=staticlib`, `#![crate_type = "staticlib"]` - A static system library will be produced. This is different from other library outputs in that the compiler will never attempt to link to `staticlib` outputs. The purpose of this output type is to create a static library containing all of the local crate’s code along with all upstream dependencies. This output type will create `*.a` files on Linux, macOS and Windows (MinGW), and `*.lib` files on Windows (MSVC). This format is recommended for use in situations such as linking Rust code into an existing non-Rust application because it will not have dynamic dependencies on other Rust code.

  Note that any dynamic dependencies that the static library may have (such as dependencies on system libraries, or dependencies on Rust libraries that are compiled as dynamic libraries) will have to be specified manually when linking that static library from somewhere. The `--print=native-static-libs` flag may help with this.

  Note that, because the resulting static library contains the code of all the dependencies, including the standard library, and also exports all public symbols of them, linking the static library into an executable or shared library may need special care. In case of a shared library the list of exported symbols will have to be limited via e.g. a linker or symbol version script, exported symbols list (macOS), or module definition file (Windows). Additionally, unused sections can be removed to remove all code of dependencies that is not actually used (e.g. `--gc-sections` or `-dead_strip` for macOS).

[link.cdylib]

- `--crate-type=cdylib`, `#![crate_type = "cdylib"]` - A dynamic system library will be produced. This is used when compiling a dynamic library to be loaded from another language. This output type will create `*.so` files on Linux, `*.dylib` files on macOS, and `*.dll` files on Windows.

[link.rlib]

- `--crate-type=rlib`, `#![crate_type = "rlib"]` - A “Rust library” file will be produced. This is used as an intermediate artifact and can be thought of as a “static Rust library”. These `rlib` files, unlike `staticlib` files, are interpreted by the compiler in future linkage. This essentially means that `rustc` will look for metadata in `rlib` files like it looks for metadata in dynamic libraries. This form of output is used to produce statically linked executables as well as `staticlib` outputs.

[link.proc-macro]

- `--crate-type=proc-macro`, `#![crate_type = "proc-macro"]` - The output produced is not specified, but if a `-L` path is provided to it then the compiler will recognize the output artifacts as a macro and it can be loaded for a program. Crates compiled with this crate type must only export procedural macros. The compiler will automatically set the `proc_macro` configuration option. The crates are always compiled with the same target that the compiler itself was built with. For example, if you are executing the compiler from Linux with an `x86_64` CPU, the target will be `x86_64-unknown-linux-gnu` even if the crate is a dependency of another crate being built for a different target.

[link.repetition]

Note that these outputs are stackable in the sense that if multiple are specified, then the compiler will produce each form of output without having to recompile. However, this only applies for outputs specified by the same method. If only `crate_type` attributes are specified, then they will all be built, but if one or more `--crate-type` command line flags are specified, then only those outputs will be built.

[link.dependency]

With all these different kinds of outputs, if crate A depends on crate B, then the compiler could find B in various different forms throughout the system. The only forms looked for by the compiler, however, are the `rlib` format and the dynamic library format. With these two options for a dependent library, the compiler must at some point make a choice between these two formats. With this in mind, the compiler follows these rules when determining what format of dependencies will be used:

[link.dependency-staticlib]

1. If a static library is being produced, all upstream dependencies are required to be available in `rlib` formats. This requirement stems from the reason that a dynamic library cannot be converted into a static format.

   Note that it is impossible to link in native dynamic dependencies to a static library, and in this case warnings will be printed about all unlinked native dynamic dependencies.

[link.dependency-rlib]

2. If an `rlib` file is being produced, then there are no restrictions on what format the upstream dependencies are available in. It is simply required that all upstream dependencies be available for reading metadata from.

   The reason for this is that `rlib` files do not contain any of their upstream dependencies. It wouldn’t be very efficient for all `rlib` files to contain a copy of `libstd.rlib`!

[link.dependency-prefer-dynamic]

3. If an executable is being produced and the `-C prefer-dynamic` flag is not specified, then dependencies are first attempted to be found in the `rlib` format. If some dependencies are not available in an rlib format, then dynamic linking is attempted (see below).

[link.dependency-dynamic]

4. If a dynamic library or an executable that is being dynamically linked is being produced, then the compiler will attempt to reconcile the available dependencies in either the rlib or dylib format to create a final product.

   A major goal of the compiler is to ensure that a library never appears more than once in any artifact. For example, if dynamic libraries B and C were each statically linked to library A, then a crate could not link to B and C together because there would be two copies of A. The compiler allows mixing the rlib and dylib formats, but this restriction must be satisfied.

   The compiler currently implements no method of hinting what format a library should be linked with. When dynamically linking, the compiler will attempt to maximize dynamic dependencies while still allowing some dependencies to be linked in via an rlib.

   For most situations, having all libraries available as a dylib is recommended if dynamically linking. For other situations, the compiler will emit a warning if it is unable to determine which formats to link each library with.

In general, `--crate-type=bin` or `--crate-type=lib` should be sufficient for all compilation needs, and the other options are just available if more fine-grained control is desired over the output format of a crate.

[link.crt]

## Static and dynamic C runtimes

[link.crt.intro]

The standard library in general strives to support both statically linked and dynamically linked C runtimes for targets as appropriate. For example the `x86_64-pc-windows-msvc` and `x86_64-unknown-linux-musl` targets typically come with both runtimes and the user selects which one they’d like. All targets in the compiler have a default mode of linking to the C runtime. Typically targets are linked dynamically by default, but there are exceptions which are static by default such as:

- `arm-unknown-linux-musleabi`
- `arm-unknown-linux-musleabihf`
- `armv7-unknown-linux-musleabihf`
- `i686-unknown-linux-musl`
- `x86_64-unknown-linux-musl`

[link.crt.crt-static]

The linkage of the C runtime is configured to respect the `crt-static` target feature. These target features are typically configured from the command line via flags to the compiler itself. For example to enable a static runtime you would execute:

    rustc -C target-feature=+crt-static foo.rs

whereas to link dynamically to the C runtime you would execute:

    rustc -C target-feature=-crt-static foo.rs

[link.crt.ineffective]

Targets which do not support switching between linkage of the C runtime will ignore this flag. It’s recommended to inspect the resulting binary to ensure that it’s linked as you would expect after the compiler succeeds.

[link.crt.target_feature]

Crates may also learn about how the C runtime is being linked. Code on MSVC, for example, needs to be compiled differently (e.g. with `/MT` or `/MD`) depending on the runtime being linked. This is exported currently through the `cfg` attribute `target_feature` option:

    #![allow(unused)]
    fn main() {
    #[cfg(target_feature = "crt-static")]
    fn foo() {
        println!("the C runtime should be statically linked");
    }

    #[cfg(not(target_feature = "crt-static"))]
    fn foo() {
        println!("the C runtime should be dynamically linked");
    }
    }

Also note that Cargo build scripts can learn about this feature through environment variables. In a build script you can detect the linkage via:

    use std::env;

    fn main() {
        let linkage = env::var("CARGO_CFG_TARGET_FEATURE").unwrap_or(String::new());

        if linkage.contains("crt-static") {
            println!("the C runtime will be statically linked");
        } else {
            println!("the C runtime will be dynamically linked");
        }
    }

To use this feature locally, you typically will use the `RUSTFLAGS` environment variable to specify flags to the compiler through Cargo. For example to compile a statically linked binary on MSVC you would execute:

    RUSTFLAGS='-C target-feature=+crt-static' cargo build --target x86_64-pc-windows-msvc

[link.foreign-code]

## Mixed Rust and foreign codebases

[link.foreign-code.foreign-linkers]

If you are mixing Rust with foreign code (e.g. C, C++) and wish to make a single binary containing both types of code, you have two approaches for the final binary link:

- Use `rustc`. Pass any non-Rust libraries using `-L <directory>` and `-l<library>` rustc arguments, and/or `#[link]` directives in your Rust code. If you need to link against `.o` files you can use `-Clink-arg=file.o`.
- Use your foreign linker. In this case, you first need to generate a Rust `staticlib` target and pass that into your foreign linker invocation. If you need to link multiple Rust subsystems, you will need to generate a single `staticlib` perhaps using lots of `extern crate` statements to include multiple Rust `rlib`s. Multiple Rust `staticlib` files are likely to conflict.

Passing `rlib`s directly into your foreign linker is currently unsupported.

> Note

> Rust code compiled or linked with a different instance of the Rust runtime counts as “foreign code” for the purpose of this section.

[link.unwinding]

### Prohibited linkage and unwinding

[link.unwinding.intro]

Panic unwinding can only be used if the binary is built consistently according to the following rules.

[link.unwinding.potential]

A Rust artifact is called potentially unwinding if any of the following conditions is met:

- The artifact uses the `unwind` panic handler.
- The artifact contains a crate built with the `unwind` panic strategy that makes a call to a function using a `-unwind` ABI.
- The artifact makes a `"Rust"` ABI call to code running in another Rust artifact that has a separate copy of the Rust runtime, and that other artifact is potentially unwinding.

> Note

> This definition captures whether a `"Rust"` ABI call inside a Rust artifact can ever unwind.

[link.unwinding.prohibited]

If a Rust artifact is potentially unwinding, then all its crates must be built with the `unwind` panic strategy. Otherwise, unwinding can cause undefined behavior.

> Note

> If you are using `rustc` to link, these rules are enforced automatically. If you are not using `rustc` to link, you must take care to ensure that unwinding is handled consistently across the entire binary. Linking without `rustc` includes using `dlopen` or similar facilities where linking is done by the system runtime without `rustc` being involved. This can only happen when mixing code with different `-C panic` flags, so most users do not have to be concerned about this.

> Note

> To guarantee that a library will be sound (and linkable with `rustc`) regardless of the panic runtime used at link-time, the `ffi_unwind_calls` lint may be used. The lint flags any calls to `-unwind` foreign functions or function pointers.

[asm]

# Inline assembly

[asm.intro]

Support for inline assembly is provided via the `asm!`, `naked_asm!`, and `global_asm!` macros. It can be used to embed handwritten assembly in the assembly output generated by the compiler.

[asm.stable-targets]

Support for inline assembly is stable on the following architectures:

- x86 and x86-64
- ARM
- AArch64 and Arm64EC
- RISC-V
- LoongArch
- s390x

The compiler will emit an error if an assembly macro is used on an unsupported target.

[asm.example]

## Example

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    use std::arch::asm;

    // Multiply x by 6 using shifts and adds
    let mut x: u64 = 4;
    unsafe {
        asm!(
            "mov {tmp}, {x}",
            "shl {tmp}, 1",
            "shl {x}, 2",
            "add {x}, {tmp}",
            x = inout(reg) x,
            tmp = out(reg) _,
        );
    }
    assert_eq!(x, 4 * 6);
    }
    }

[asm.syntax]

## Syntax

The following grammar specifies the arguments that can be passed to the `asm!`, `global_asm!` and `naked_asm!` macros.

Syntax
AsmArgs → AsmAttrFormatString ( , AsmAttrFormatString )* ( , AsmAttrOperand )* ,?

FormatString → STRING_LITERAL | RAW_STRING_LITERAL | MacroInvocation

AsmAttrFormatString → ( OuterAttribute )* FormatString

AsmOperand →
ClobberAbi
| AsmOptions
| RegOperand

AsmAttrOperand → ( OuterAttribute )* AsmOperand

ClobberAbi → clobber_abi ( Abi ( , Abi )* ,? )

AsmOptions →
options ( ( AsmOption ( , AsmOption )* ,? )? )

AsmOption →
pure
| nomem
| readonly
| preserves_flags
| noreturn
| nostack
| att_syntax
| raw

RegOperand → ( ParamName = )?
(
DirSpec ( RegSpec ) Expression
| DualDirSpec ( RegSpec ) DualDirSpecExpression
| sym PathExpression
| const Expression
| label { Statements? }
)

ParamName → IDENTIFIER_OR_KEYWORD | RAW_IDENTIFIER

DualDirSpecExpression →
Expression
| Expression => Expression

RegSpec → RegisterClass | ExplicitRegister

RegisterClass → IDENTIFIER_OR_KEYWORD

ExplicitRegister → STRING_LITERAL

DirSpec →
in
| out
| lateout

DualDirSpec →
inout
| inlateout

[asm.scope]

## Scope

[asm.scope.intro]

Inline assembly can be used in one of three ways.

[asm.scope.asm]

With the `asm!` macro, the assembly code is emitted in a function scope and integrated into the compiler-generated assembly code of a function. This assembly code must obey strict rules to avoid undefined behavior. Note that in some cases the compiler may choose to emit the assembly code as a separate function and generate a call to it.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    unsafe { core::arch::asm!("/* {} */", in(reg) 0); }
    }
    }

[asm.scope.naked_asm]

With the `naked_asm!` macro, the assembly code is emitted in a function scope and constitutes the full assembly code of a function. The `naked_asm!` macro is only allowed in naked functions.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    #[unsafe(naked)]
    extern "C" fn wrapper() {
    core::arch::naked_asm!("/* {} */", const 0);
    }
    }
    }

[asm.scope.global_asm]

With the `global_asm!` macro, the assembly code is emitted in a global scope, outside a function. This can be used to hand-write entire functions using assembly code, and generally provides much more freedom to use arbitrary registers and assembler directives.

    fn main() {}
    #[cfg(target_arch = "x86_64")]
    core::arch::global_asm!("/* {} */", const 0);

[asm.ts-args]

## Template string arguments

[asm.ts-args.syntax]

The assembler template uses the same syntax as format strings (i.e. placeholders are specified by curly braces).

[asm.ts-args.order]

The corresponding arguments are accessed in order, by index, or by name.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64;
    let y: i64;
    let z: i64;
    // This
    unsafe { core::arch::asm!("mov {}, {}", out(reg) x, in(reg) 5); }
    // ... this
    unsafe { core::arch::asm!("mov {0}, {1}", out(reg) y, in(reg) 5); }
    // ... and this
    unsafe { core::arch::asm!("mov {out}, {in}", out = out(reg) z, in = in(reg) 5); }
    // all have the same behavior
    assert_eq!(x, y);
    assert_eq!(y, z);
    }
    }

[asm.ts-args.no-implicit]

However, implicit named arguments (introduced by RFC #2795) are not supported.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x = 5;
    // We can't refer to `x` from the scope directly, we need an operand like `in(reg) x`
    unsafe { core::arch::asm!("/* {x} */"); } // ERROR: no argument named x
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.ts-args.one-or-more]

An `asm!` invocation may have one or more template string arguments; an `asm!` with multiple template string arguments is treated as if all the strings were concatenated with a `\n` between them. The expected usage is for each template string argument to correspond to a line of assembly code.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64;
    let y: i64;
    // We can separate multiple strings as if they were written together
    unsafe { core::arch::asm!("mov eax, 5", "mov ecx, eax", out("rax") x, out("rcx") y); }
    assert_eq!(x, y);
    }
    }

[asm.ts-args.before-other-args]

All template string arguments must appear before any other arguments.

    #![allow(unused)]
    fn main() {
    let x = 5;
    #[cfg(target_arch = "x86_64")] {
    // The template strings need to appear first in the asm invocation
    unsafe { core::arch::asm!("/* {x} */", x = const 5, "ud2"); } // ERROR: unexpected token
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.ts-args.positional-first]

As with format strings, positional arguments must appear before named arguments and explicit register operands.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // Named operands need to come after positional ones
    unsafe { core::arch::asm!("/* {x} {} */", x = const 5, in(reg) 5); }
    // ERROR: positional arguments cannot follow named arguments or explicit register arguments
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // We also can't put explicit registers before positional operands
    unsafe { core::arch::asm!("/* {} */", in("eax") 0, in(reg) 5); }
    // ERROR: positional arguments cannot follow named arguments or explicit register arguments
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.ts-args.register-operands]

Explicit register operands cannot be used by placeholders in the template string.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // Explicit register operands don't get substituted, use `eax` explicitly in the string
    unsafe { core::arch::asm!("/* {} */", in("eax") 5); }
    // ERROR: invalid reference to argument at index 0
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.ts-args.at-least-once]

All other named and positional operands must appear at least once in the template string, otherwise a compiler error is generated.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // We have to name all of the operands in the format string
    unsafe { core::arch::asm!("", in(reg) 5, x = const 5); }
    // ERROR: multiple unused asm arguments
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.ts-args.opaque]

The exact assembly code syntax is target-specific and opaque to the compiler except for the way operands are substituted into the template string to form the code passed to the assembler.

[asm.ts-args.llvm-syntax]

Currently, all supported targets follow the assembly code syntax used by LLVM’s internal assembler which usually corresponds to that of the GNU assembler (GAS). On x86, the `.intel_syntax noprefix` mode of GAS is used by default. On ARM, the `.syntax unified` mode is used. These targets impose an additional restriction on the assembly code: any assembler state (e.g. the current section which can be changed with `.section`) must be restored to its original value at the end of the asm string. Assembly code that does not conform to the GAS syntax will result in assembler-specific behavior. Further constraints on the directives used by inline assembly are indicated by Directives Support.

[asm.attributes]

## Attributes

[asm.attributes.supported-attributes]

Only the `cfg` and `cfg_attr` attributes are accepted semantically on inline assembly template strings and operands. Other attributes are parsed but rejected when the assembly macro is expanded.

    fn main() {}
    #[cfg(target_arch = "x86_64")]
    core::arch::global_asm!(
        #[cfg(not(panic = "abort"))]
        ".cfi_startproc",
        // ...
        "ret",
        #[cfg(not(panic = "abort"))]
        ".cfi_endproc",
    );

> Note

> In `rustc`, the assembly macros implement handling of these attributes separately from the normal system that handles similar attributes in the language. This accounts for the limited kinds of attributes supported and may give rise to subtle differences in behavior.

[asm.attributes.starts-with-template]

Syntactically there must be at least one template string before the first operand.

    #![allow(unused)]
    fn main() {
    // This is rejected because `a = out(reg) x` does not parse as a
    // template string.
    core::arch::asm!(
        #[cfg(false)]
        a = out(reg) x, // ERROR.
        "",
    );
    }

[asm.operand-type]

## Operand type

[asm.operand-type.supported-operands]

Several types of operands are supported:

[asm.operand-type.supported-operands.in]

- `in(<reg>) <expr>`
  - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
  - The allocated register will contain the value of `<expr>` at the start of the assembly code.
  - The allocated register must contain the same value at the end of the assembly code (except if a `lateout` is allocated to the same register).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // ``in` can be used to pass values into inline assembly...
    unsafe { core::arch::asm!("/* {} */", in(reg) 5); }
    }
    }

[asm.operand-type.supported-operands.out]

- `out(<reg>) <expr>`
  - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
  - The allocated register will contain an undefined value at the start of the assembly code.
  - `<expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the assembly code.
  - An underscore (`_`) may be specified instead of an expression, which will cause the contents of the register to be discarded at the end of the assembly code (effectively acting as a clobber).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64;
    // and `out` can be used to pass values back to rust.
    unsafe { core::arch::asm!("/* {} */", out(reg) x); }
    }
    }

[asm.operand-type.supported-operands.lateout]

- `lateout(<reg>) <expr>`
  - Identical to `out` except that the register allocator can reuse a register allocated to an `in`.
  - You should only write to the register after all inputs are read, otherwise you may clobber an input.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64;
    // `lateout` is the same as `out`
    // but the compiler knows we don't care about the value of any inputs by the
    // time we overwrite it.
    unsafe { core::arch::asm!("mov {}, 5", lateout(reg) x); }
    assert_eq!(x, 5)
    }
    }

[asm.operand-type.supported-operands.inout]

- `inout(<reg>) <expr>`
  - `<reg>` can refer to a register class or an explicit register. The allocated register name is substituted into the asm template string.
  - The allocated register will contain the value of `<expr>` at the start of the assembly code.
  - `<expr>` must be a mutable initialized place expression, to which the contents of the allocated register are written at the end of the assembly code.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x: i64 = 4;
    // `inout` can be used to modify values in-register
    unsafe { core::arch::asm!("inc {}", inout(reg) x); }
    assert_eq!(x, 5);
    }
    }

[asm.operand-type.supported-operands.inout-arrow]

- `inout(<reg>) <in expr> => <out expr>`
  - Same as `inout` except that the initial value of the register is taken from the value of `<in expr>`.
  - `<out expr>` must be a (possibly uninitialized) place expression, to which the contents of the allocated register are written at the end of the assembly code.
  - An underscore (`_`) may be specified instead of an expression for `<out expr>`, which will cause the contents of the register to be discarded at the end of the assembly code (effectively acting as a clobber).
  - `<in expr>` and `<out expr>` may have different types.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64;
    // `inout` can also move values to different places
    unsafe { core::arch::asm!("inc {}", inout(reg) 4u64=>x); }
    assert_eq!(x, 5);
    }
    }

[asm.operand-type.supported-operands.inlateout]

- `inlateout(<reg>) <expr>` / `inlateout(<reg>) <in expr> => <out expr>`
  - Identical to `inout` except that the register allocator can reuse a register allocated to an `in` (this can happen if the compiler knows the `in` has the same initial value as the `inlateout`).
  - You should only write to the register after all inputs are read, otherwise you may clobber an input.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x: i64 = 4;
    // `inlateout` is `inout` using `lateout`
    unsafe { core::arch::asm!("inc {}", inlateout(reg) x); }
    assert_eq!(x, 5);
    }
    }

[asm.operand-type.supported-operands.sym]

- `sym <path>`
  - `<path>` must refer to a `fn` or `static`.
  - A mangled symbol name referring to the item is substituted into the asm template string.
  - The substituted string does not include any modifiers (e.g. GOT, PLT, relocations, etc).
  - `<path>` is allowed to point to a `#[thread_local]` static, in which case the assembly code can combine the symbol with relocations (e.g. `@plt`, `@TPOFF`) to read from thread-local data.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    extern "C" fn foo() {
        println!("Hello from inline assembly")
    }
    // `sym` can be used to refer to a function (even if it doesn't have an
    // external name we can directly write)
    unsafe { core::arch::asm!("call {}", sym foo, clobber_abi("C")); }
    }
    }

[asm.operand-type.supported-operands.const]

- `const <expr>`
  - `<expr>` must be an integer constant expression. This expression follows the same rules as inline `const` blocks.
  - The type of the expression may be any integer type, but defaults to `i32` just like integer literals.
  - The value of the expression is formatted as a string and substituted directly into the asm template string.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // swizzle [0, 1, 2, 3] => [3, 2, 0, 1]
    const SHUFFLE: u8 = 0b01_00_10_11;
    let x: core::arch::x86_64::__m128 = unsafe { core::mem::transmute([0u32, 1u32, 2u32, 3u32]) };
    let y: core::arch::x86_64::__m128;
    // Pass a constant value into an instruction that expects an immediate like `pshufd`
    unsafe {
        core::arch::asm!("pshufd {xmm}, {xmm}, {shuffle}",
            xmm = inlateout(xmm_reg) x=>y,
            shuffle = const SHUFFLE
        );
    }
    let y: [u32; 4] = unsafe { core::mem::transmute(y) };
    assert_eq!(y, [3, 2, 0, 1]);
    }
    }

[asm.operand-type.supported-operands.label]
Tests
Tests with this rule:

- tests/ui/asm/label-operand.rs

- `label <block>`
  - The address of the block is substituted into the asm template string. The assembly code may jump to the substituted address.
  - For targets that distinguish between direct jumps and indirect jumps (e.g. x86-64 with `cf-protection` enabled), the assembly code must not jump to the substituted address indirectly.
  - After execution of the block, the `asm!` expression returns.
  - The type of the block must be unit or `!` (never).
  - The block starts a new safety context; unsafe operations within the `label` block must be wrapped in an inner `unsafe` block, even though the entire `asm!` expression is already wrapped in `unsafe`.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")]
    unsafe {
        core::arch::asm!("jmp {}", label {
            println!("Hello from inline assembly label");
        });
    }
    }

[asm.operand-type.left-to-right]

Operand expressions are evaluated from left to right, just like function call arguments. After the `asm!` has executed, outputs are written to in left to right order. This is significant if two outputs point to the same place: that place will contain the value of the rightmost output.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut y: i64;
    // y gets its value from the second output, rather than the first
    unsafe { core::arch::asm!("mov {}, 0", "mov {}, 1", out(reg) y, out(reg) y); }
    assert_eq!(y, 1);
    }
    }

[asm.operand-type.naked_asm-restriction]

Because `naked_asm!` defines a whole function body and the compiler cannot emit any additional code to handle operands, it can only use `sym` and `const` operands.

[asm.operand-type.global_asm-restriction]

Because `global_asm!` exists outside a function, it can only use `sym` and `const` operands.

    fn main() {}
    // register operands aren't allowed, since we aren't in a function
    #[cfg(target_arch = "x86_64")]
    core::arch::global_asm!("", in(reg) 5);
    // ERROR: the `in` operand cannot be used with `global_asm!`
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");

    fn main() {}
    fn foo() {}

    #[cfg(target_arch = "x86_64")]
    // `const` and `sym` are both allowed, however
    core::arch::global_asm!("/* {} {} */", const 0, sym foo);

[asm.register-operands]

## Register operands

[asm.register-operands.register-or-class]

Input and output operands can be specified either as an explicit register or as a register class from which the register allocator can select a register. Explicit registers are specified as string literals (e.g. `"eax"`) while register classes are specified as identifiers (e.g. `reg`).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut y: i64;
    // We can name both `reg`, or an explicit register like `eax` to get an
    // integer register
    unsafe { core::arch::asm!("mov eax, {:e}", in(reg) 5, lateout("eax") y); }
    assert_eq!(y, 5);
    }
    }

[asm.register-operands.equivalence-to-base-register]

Note that explicit registers treat register aliases (e.g. `r14` vs `lr` on ARM) and smaller views of a register (e.g. `eax` vs `rax`) as equivalent to the base register.

[asm.register-operands.error-two-operands]

It is a compile-time error to use the same explicit register for two input operands or two output operands.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // We can't name eax twice
    unsafe { core::arch::asm!("", in("eax") 5, in("eax") 4); }
    // ERROR: register `eax` conflicts with register `eax`
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // ... even using different aliases
    unsafe { core::arch::asm!("", in("ax") 5, in("rax") 4); }
    // ERROR: register `rax` conflicts with register `ax`
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-operands.error-overlapping]

Additionally, it is also a compile-time error to use overlapping registers (e.g. ARM VFP) in input operands or in output operands.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // al overlaps with ax, so we can't name both of them.
    unsafe { core::arch::asm!("", in("ax") 5, in("al") 4i8); }
    // ERROR: register `al` conflicts with register `ax`
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-operands.allowed-types]

Only the following types are allowed as operands for inline assembly:

- Integers (signed and unsigned)
- Floating-point numbers
- Pointers (thin only)
- Function pointers
- SIMD vectors (structs defined with `#[repr(simd)]` and which implement `Copy`). This includes architecture-specific vector types defined in `std::arch` such as `__m128` (x86) or `int8x16_t` (ARM).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    extern "C" fn foo() {}

    // Integers are allowed...
    let y: i64 = 5;
    unsafe { core::arch::asm!("/* {} */", in(reg) y); }

    // and pointers...
    let py = &raw const y;
    unsafe { core::arch::asm!("/* {} */", in(reg) py); }

    // floats as well...
    let f = 1.0f32;
    unsafe { core::arch::asm!("/* {} */", in(xmm_reg) f); }

    // even function pointers and simd vectors.
    let func: extern "C" fn() = foo;
    unsafe { core::arch::asm!("/* {} */", in(reg) func); }

    let z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };
    unsafe { core::arch::asm!("/* {} */", in(xmm_reg) z); }
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    struct Foo;
    let x: Foo = Foo;
    // Complex types like structs are not allowed
    unsafe { core::arch::asm!("/* {} */", in(reg) x); }
    // ERROR: cannot use value of type `Foo` for inline assembly
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-operands.supported-register-classes]

Here is the list of currently supported register classes:

Architecture | Register class | Registers | LLVM constraint code
--- | --- | --- | ---
x86 | `reg` | `ax`, `bx`, `cx`, `dx`, `si`, `di`, `bp`, `r[8-15]` (x86-64 only) | `r`
x86 | `reg_abcd` | `ax`, `bx`, `cx`, `dx` | `Q`
x86-32 | `reg_byte` | `al`, `bl`, `cl`, `dl`, `ah`, `bh`, `ch`, `dh` | `q`
x86-64 | `reg_byte`* | `al`, `bl`, `cl`, `dl`, `sil`, `dil`, `bpl`, `r[8-15]b` | `q`
x86 | `xmm_reg` | `xmm[0-7]` (x86) `xmm[0-15]` (x86-64) | `x`
x86 | `ymm_reg` | `ymm[0-7]` (x86) `ymm[0-15]` (x86-64) | `x`
x86 | `zmm_reg` | `zmm[0-7]` (x86) `zmm[0-31]` (x86-64) | `v`
x86 | `kreg` | `k[1-7]` | `Yk`
x86 | `kreg0` | `k0` | Only clobbers
x86 | `x87_reg` | `st([0-7])` | Only clobbers
x86 | `mmx_reg` | `mm[0-7]` | Only clobbers
x86-64 | `tmm_reg` | `tmm[0-7]` | Only clobbers
AArch64 | `reg` | `x[0-30]` | `r`
AArch64 | `vreg` | `v[0-31]` | `w`
AArch64 | `vreg_low16` | `v[0-15]` | `x`
AArch64 | `preg` | `p[0-15]`, `ffr` | Only clobbers
Arm64EC | `reg` | `x[0-12]`, `x[15-22]`, `x[25-27]`, `x30` | `r`
Arm64EC | `vreg` | `v[0-15]` | `w`
Arm64EC | `vreg_low16` | `v[0-15]` | `x`
ARM (ARM/Thumb2) | `reg` | `r[0-12]`, `r14` | `r`
ARM (Thumb1) | `reg` | `r[0-7]` | `r`
ARM | `sreg` | `s[0-31]` | `t`
ARM | `sreg_low16` | `s[0-15]` | `x`
ARM | `dreg` | `d[0-31]` | `w`
ARM | `dreg_low16` | `d[0-15]` | `t`
ARM | `dreg_low8` | `d[0-8]` | `x`
ARM | `qreg` | `q[0-15]` | `w`
ARM | `qreg_low8` | `q[0-7]` | `t`
ARM | `qreg_low4` | `q[0-3]` | `x`
RISC-V | `reg` | `x1`, `x[5-7]`, `x[9-15]`, `x[16-31]` (non-RV32E) | `r`
RISC-V | `freg` | `f[0-31]` | `f`
RISC-V | `vreg` | `v[0-31]` | Only clobbers
LoongArch | `reg` | `$r1`, `$r[4-20]`, `$r[23,30]` | `r`
LoongArch | `freg` | `$f[0-31]` | `f`
s390x | `reg` | `r[0-10]`, `r[12-14]` | `r`
s390x | `reg_addr` | `r[1-10]`, `r[12-14]` | `a`
s390x | `freg` | `f[0-15]` | `f`
s390x | `vreg` | `v[0-31]` | Only clobbers
s390x | `areg` | `a[2-15]` | Only clobbers

> Note

> - On x86 we treat `reg_byte` differently from `reg` because the compiler can allocate `al` and `ah` separately whereas `reg` reserves the whole register.
> - On x86-64 the high byte registers (e.g. `ah`) are not available in the `reg_byte` register class.
> - Some register classes are marked as “Only clobbers” which means that registers in these classes cannot be used for inputs or outputs, only clobbers of the form `out(<explicit register>) _` or `lateout(<explicit register>) _`.

[asm.register-operands.value-type-constraints]

Each register class has constraints on which value types they can be used with. This is necessary because the way a value is loaded into a register depends on its type. For example, on big-endian systems, loading a `i32x4` and a `i8x16` into a SIMD register may result in different register contents even if the byte-wise memory representation of both values is identical. The availability of supported types for a particular register class may depend on what target features are currently enabled.

Architecture | Register class | Target feature | Allowed types
--- | --- | --- | ---
x86-32 | `reg` | None | `i16`, `i32`, `f32`
x86-64 | `reg` | None | `i16`, `i32`, `f32`, `i64`, `f64`
x86 | `reg_byte` | None | `i8`
x86 | `xmm_reg` | `sse` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`
x86 | `ymm_reg` | `avx` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4`
x86 | `zmm_reg` | `avx512f` | `i32`, `f32`, `i64`, `f64`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2` `i8x32`, `i16x16`, `i32x8`, `i64x4`, `f32x8`, `f64x4` `i8x64`, `i16x32`, `i32x16`, `i64x8`, `f32x16`, `f64x8`
x86 | `kreg` | `avx512f` | `i8`, `i16`
x86 | `kreg` | `avx512bw` | `i32`, `i64`
x86 | `mmx_reg` | N/A | Only clobbers
x86 | `x87_reg` | N/A | Only clobbers
x86 | `tmm_reg` | N/A | Only clobbers
AArch64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`
AArch64 | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`
AArch64 | `preg` | N/A | Only clobbers
Arm64EC | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`
Arm64EC | `vreg` | `neon` | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`, `f64x1`, `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`, `f64x2`
ARM | `reg` | None | `i8`, `i16`, `i32`, `f32`
ARM | `sreg` | `vfp2` | `i32`, `f32`
ARM | `dreg` | `vfp2` | `i64`, `f64`, `i8x8`, `i16x4`, `i32x2`, `i64x1`, `f32x2`
ARM | `qreg` | `neon` | `i8x16`, `i16x8`, `i32x4`, `i64x2`, `f32x4`
RISC-V32 | `reg` | None | `i8`, `i16`, `i32`, `f32`
RISC-V64 | `reg` | None | `i8`, `i16`, `i32`, `f32`, `i64`, `f64`
RISC-V | `freg` | `f` | `f32`
RISC-V | `freg` | `d` | `f64`
RISC-V | `vreg` | N/A | Only clobbers
LoongArch32 | `reg` | None | `i8`, `i16`, `i32`, `f32`
LoongArch64 | `reg` | None | `i8`, `i16`, `i32`, `i64`, `f32`, `f64`
LoongArch | `freg` | `f` | `f32`
LoongArch | `freg` | `d` | `f64`
s390x | `reg`, `reg_addr` | None | `i8`, `i16`, `i32`, `i64`
s390x | `freg` | None | `f32`, `f64`
s390x | `vreg` | N/A | Only clobbers
s390x | `areg` | N/A | Only clobbers

> Note

> For the purposes of the above table pointers, function pointers and `isize`/`usize` are treated as the equivalent integer type (`i16`/`i32`/`i64` depending on the target).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x = 5i32;
    let y = -1i8;
    let z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };

    // reg is valid for `i32`, `reg_byte` is valid for `i8`, and xmm_reg is valid for `__m128i`
    // We can't use `tmm0` as an input or output, but we can clobber it.
    unsafe { core::arch::asm!("/* {} {} {} */", in(reg) x, in(reg_byte) y, in(xmm_reg) z, out("tmm0") _); }
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let z = unsafe { core::arch::x86_64::_mm_set_epi64x(1, 0) };
    // We can't pass an `__m128i` to a `reg` input
    unsafe { core::arch::asm!("/* {} */", in(reg) z); }
    // ERROR: type `__m128i` cannot be used with this register class
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-operands.smaller-value]

If a value is of a smaller size than the register it is allocated in then the upper bits of that register will have an undefined value for inputs and will be ignored for outputs. The only exception is the `freg` register class on RISC-V where `f32` values are NaN-boxed in a `f64` as required by the RISC-V architecture.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x: i64;
    // Moving a 32-bit value into a 64-bit value, oops.
    #[allow(asm_sub_register)] // rustc warns about this behavior
    unsafe { core::arch::asm!("mov {}, {}", lateout(reg) x, in(reg) 4i32); }
    // top 32-bits are indeterminate
    assert_eq!(x, 4); // This assertion is not guaranteed to succeed
    assert_eq!(x & 0xFFFFFFFF, 4); // However, this one will succeed
    }
    }

[asm.register-operands.separate-input-output]

When separate input and output expressions are specified for an `inout` operand, both expressions must have the same type. The only exception is if both operands are pointers or integers, in which case they are only required to have the same size. This restriction exists because the register allocators in LLVM and GCC sometimes cannot handle tied operands with different types.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // Pointers and integers can mix (as long as they are the same size)
    let x: isize = 0;
    let y: *mut ();
    // Transmute an `isize` to a `*mut ()`, using inline assembly magic
    unsafe { core::arch::asm!("/*{}*/", inout(reg) x=>y); }
    assert!(y.is_null()); // Extremely roundabout way to make a null pointer
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i32 = 0;
    let y: f32;
    // But we can't reinterpret an `i32` to an `f32` like this
    unsafe { core::arch::asm!("/* {} */", inout(reg) x=>y); }
    // ERROR: incompatible types for asm inout argument
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-names]

## Register names

[asm.register-names.supported-register-aliases]

Some registers have multiple names. These are all treated by the compiler as identical to the base register name. Here is the list of all supported register aliases:

Architecture | Base register | Aliases
--- | --- | ---
x86 | `ax` | `eax`, `rax`
x86 | `bx` | `ebx`, `rbx`
x86 | `cx` | `ecx`, `rcx`
x86 | `dx` | `edx`, `rdx`
x86 | `si` | `esi`, `rsi`
x86 | `di` | `edi`, `rdi`
x86 | `bp` | `bpl`, `ebp`, `rbp`
x86 | `sp` | `spl`, `esp`, `rsp`
x86 | `ip` | `eip`, `rip`
x86 | `st(0)` | `st`
x86 | `r[8-15]` | `r[8-15]b`, `r[8-15]w`, `r[8-15]d`
x86 | `xmm[0-31]` | `ymm[0-31]`, `zmm[0-31]`
AArch64 | `x[0-30]` | `w[0-30]`
AArch64 | `x29` | `fp`
AArch64 | `x30` | `lr`
AArch64 | `sp` | `wsp`
AArch64 | `xzr` | `wzr`
AArch64 | `v[0-31]` | `b[0-31]`, `h[0-31]`, `s[0-31]`, `d[0-31]`, `q[0-31]`
Arm64EC | `x[0-30]` | `w[0-30]`
Arm64EC | `x29` | `fp`
Arm64EC | `x30` | `lr`
Arm64EC | `sp` | `wsp`
Arm64EC | `xzr` | `wzr`
Arm64EC | `v[0-15]` | `b[0-15]`, `h[0-15]`, `s[0-15]`, `d[0-15]`, `q[0-15]`
ARM | `r[0-3]` | `a[1-4]`
ARM | `r[4-9]` | `v[1-6]`
ARM | `r9` | `rfp`
ARM | `r10` | `sl`
ARM | `r11` | `fp`
ARM | `r12` | `ip`
ARM | `r13` | `sp`
ARM | `r14` | `lr`
ARM | `r15` | `pc`
RISC-V | `x0` | `zero`
RISC-V | `x1` | `ra`
RISC-V | `x2` | `sp`
RISC-V | `x3` | `gp`
RISC-V | `x4` | `tp`
RISC-V | `x[5-7]` | `t[0-2]`
RISC-V | `x8` | `fp`, `s0`
RISC-V | `x9` | `s1`
RISC-V | `x[10-17]` | `a[0-7]`
RISC-V | `x[18-27]` | `s[2-11]`
RISC-V | `x[28-31]` | `t[3-6]`
RISC-V | `f[0-7]` | `ft[0-7]`
RISC-V | `f[8-9]` | `fs[0-1]`
RISC-V | `f[10-17]` | `fa[0-7]`
RISC-V | `f[18-27]` | `fs[2-11]`
RISC-V | `f[28-31]` | `ft[8-11]`
LoongArch | `$r0` | `$zero`
LoongArch | `$r1` | `$ra`
LoongArch | `$r2` | `$tp`
LoongArch | `$r3` | `$sp`
LoongArch | `$r[4-11]` | `$a[0-7]`
LoongArch | `$r[12-20]` | `$t[0-8]`
LoongArch | `$r21` |
LoongArch | `$r22` | `$fp`, `$s9`
LoongArch | `$r[23-31]` | `$s[0-8]`
LoongArch | `$f[0-7]` | `$fa[0-7]`
LoongArch | `$f[8-23]` | `$ft[0-15]`
LoongArch | `$f[24-31]` | `$fs[0-7]`

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let z = 0i64;
    // rax is an alias for eax and ax
    unsafe { core::arch::asm!("", in("rax") z); }
    }
    }

[asm.register-names.not-for-io]

Some registers cannot be used for input or output operands:

Architecture | Unsupported register | Reason
--- | --- | ---
All | `sp`, `r15` (s390x) | The stack pointer must be restored to its original value at the end of the assembly code or before jumping to a `label` block.
All | `bp` (x86), `x29` (AArch64 and Arm64EC), `x8` (RISC-V), `$fp` (LoongArch), `r11` (s390x) | The frame pointer cannot be used as an input or output.
ARM | `r7` or `r11` | On ARM the frame pointer can be either `r7` or `r11` depending on the target. The frame pointer cannot be used as an input or output.
All | `si` (x86-32), `bx` (x86-64), `r6` (ARM), `x19` (AArch64 and Arm64EC), `x9` (RISC-V), `$s8` (LoongArch) | This is used internally by LLVM as a “base pointer” for functions with complex stack frames.
x86 | `ip` | This is the program counter, not a real register.
AArch64 | `xzr` | This is a constant zero register which can’t be modified.
AArch64 | `x18` | This is an OS-reserved register on some AArch64 targets.
Arm64EC | `xzr` | This is a constant zero register which can’t be modified.
Arm64EC | `x18` | This is an OS-reserved register.
Arm64EC | `x13`, `x14`, `x23`, `x24`, `x28`, `v[16-31]`, `p[0-15]`, `ffr` | These are AArch64 registers that are not supported for Arm64EC.
ARM | `pc` | This is the program counter, not a real register.
ARM | `r9` | This is an OS-reserved register on some ARM targets.
RISC-V | `x0` | This is a constant zero register which can’t be modified.
RISC-V | `gp`, `tp` | These registers are reserved and cannot be used as inputs or outputs.
LoongArch | `$r0` or `$zero` | This is a constant zero register which can’t be modified.
LoongArch | `$r2` or `$tp` | This is reserved for TLS.
LoongArch | `$r21` | This is reserved by the ABI.
s390x | `c[0-15]` | Reserved by the kernel.
s390x | `a[0-1]` | Reserved for system use.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // bp is reserved
    unsafe { core::arch::asm!("", in("bp") 5i32); }
    // ERROR: invalid register `bp`: the frame pointer cannot be used as an operand for inline asm
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.register-names.fp-bp-reserved]

The frame pointer and base pointer registers are reserved for internal use by LLVM. While `asm!` statements cannot explicitly specify the use of reserved registers, in some cases LLVM will allocate one of these reserved registers for `reg` operands. Assembly code making use of reserved registers should be careful since `reg` operands may use the same registers.

[asm.template-modifiers]

## Template modifiers

[asm.template-modifiers.intro]

The placeholders can be augmented by modifiers which are specified after the `:` in the curly braces. These modifiers do not affect register allocation, but change the way operands are formatted when inserted into the template string.

[asm.template-modifiers.only-one]

Only one modifier is allowed per template placeholder.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // We can't specify both `r` and `e` at the same time.
    unsafe { core::arch::asm!("/* {:er}", in(reg) 5i32); }
    // ERROR: asm template modifier must be a single character
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.template-modifiers.supported-modifiers]

The supported modifiers are a subset of LLVM’s (and GCC’s) asm template argument modifiers, but do not use the same letter codes.

Architecture | Register class | Modifier | Example output | LLVM modifier
--- | --- | --- | --- | ---
x86-32 | `reg` | None | `eax` | `k`
x86-64 | `reg` | None | `rax` | `q`
x86-32 | `reg_abcd` | `l` | `al` | `b`
x86-64 | `reg` | `l` | `al` | `b`
x86 | `reg_abcd` | `h` | `ah` | `h`
x86 | `reg` | `x` | `ax` | `w`
x86 | `reg` | `e` | `eax` | `k`
x86-64 | `reg` | `r` | `rax` | `q`
x86 | `reg_byte` | None | `al` / `ah` | None
x86 | `xmm_reg` | None | `xmm0` | `x`
x86 | `ymm_reg` | None | `ymm0` | `t`
x86 | `zmm_reg` | None | `zmm0` | `g`
x86 | `*mm_reg` | `x` | `xmm0` | `x`
x86 | `*mm_reg` | `y` | `ymm0` | `t`
x86 | `*mm_reg` | `z` | `zmm0` | `g`
x86 | `kreg` | None | `k1` | None
AArch64/Arm64EC | `reg` | None | `x0` | `x`
AArch64/Arm64EC | `reg` | `w` | `w0` | `w`
AArch64/Arm64EC | `reg` | `x` | `x0` | `x`
AArch64/Arm64EC | `vreg` | None | `v0` | None
AArch64/Arm64EC | `vreg` | `v` | `v0` | None
AArch64/Arm64EC | `vreg` | `b` | `b0` | `b`
AArch64/Arm64EC | `vreg` | `h` | `h0` | `h`
AArch64/Arm64EC | `vreg` | `s` | `s0` | `s`
AArch64/Arm64EC | `vreg` | `d` | `d0` | `d`
AArch64/Arm64EC | `vreg` | `q` | `q0` | `q`
ARM | `reg` | None | `r0` | None
ARM | `sreg` | None | `s0` | None
ARM | `dreg` | None | `d0` | `P`
ARM | `qreg` | None | `q0` | `q`
ARM | `qreg` | `e` / `f` | `d0` / `d1` | `e` / `f`
RISC-V | `reg` | None | `x1` | None
RISC-V | `freg` | None | `f0` | None
LoongArch | `reg` | None | `$r1` | None
LoongArch | `freg` | None | `$f0` | None
s390x | `reg` | None | `%r0` | None
s390x | `reg_addr` | None | `%r1` | None
s390x | `freg` | None | `%f0` | None

> Note

> - on ARM `e` / `f`: this prints the low or high doubleword register name of a NEON quad (128-bit) register.
> - on x86: our behavior for `reg` with no modifiers differs from what GCC does. GCC will infer the modifier based on the operand value type, while we default to the full register size.
> - on x86 `xmm_reg`: the `x`, `t` and `g` LLVM modifiers are not yet implemented in LLVM (they are supported by GCC only), but this should be a simple change.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x = 0x10u16;

    // u16::swap_bytes using `xchg`
    // low half of `{x}` is referred to by `{x:l}`, and the high half by `{x:h}`
    unsafe { core::arch::asm!("xchg {x:l}, {x:h}", x = inout(reg_abcd) x); }
    assert_eq!(x, 0x1000u16);
    }
    }

[asm.template-modifiers.smaller-value]

As stated in the previous section, passing an input value smaller than the register width will result in the upper bits of the register containing undefined values. This is not a problem if the inline asm only accesses the lower bits of the register, which can be done by using a template modifier to use a subregister name in the assembly code (e.g. `ax` instead of `rax`). Since this an easy pitfall, the compiler will suggest a template modifier to use where appropriate given the input type. If all references to an operand already have modifiers then the warning is suppressed for that operand.

[asm.abi-clobbers]

## ABI clobbers

[asm.abi-clobbers.intro]

The `clobber_abi` keyword can be used to apply a default set of clobbers to the assembly code. This will automatically insert the necessary clobber constraints as needed for calling a function with a particular calling convention: if the calling convention does not fully preserve the value of a register across a call then `lateout("...") _` is implicitly added to the operands list (where the `...` is replaced by the register’s name).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    extern "C" fn foo() -> i32 { 0 }

    let z: i32;
    // To call a function, we have to inform the compiler that we're clobbering
    // callee saved registers
    unsafe { core::arch::asm!("call {}", sym foo, out("rax") z, clobber_abi("C")); }
    assert_eq!(z, 0);
    }
    }

[asm.abi-clobbers.many]

`clobber_abi` may be specified any number of times. It will insert a clobber for all unique registers in the union of all specified calling conventions.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    extern "sysv64" fn foo() -> i32 { 0 }
    extern "win64" fn bar(x: i32) -> i32 { x + 1}

    let z: i32;
    // We can even call multiple functions with different conventions and
    // different saved registers
    unsafe {
        core::arch::asm!(
            "call {}",
            "mov ecx, eax",
            "call {}",
            sym foo,
            sym bar,
            out("rax") z,
            clobber_abi("C")
        );
    }
    assert_eq!(z, 1);
    }
    }

[asm.abi-clobbers.must-specify]

Generic register class outputs are disallowed by the compiler when `clobber_abi` is used: all outputs must specify an explicit register.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    extern "C" fn foo(x: i32) -> i32 { 0 }

    let z: i32;
    // explicit registers must be used to not accidentally overlap.
    unsafe {
        core::arch::asm!(
            "mov eax, {:e}",
            "call {}",
            out(reg) z,
            sym foo,
            clobber_abi("C")
        );
        // ERROR: asm with `clobber_abi` must specify explicit registers for outputs
    }
    assert_eq!(z, 0);
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.abi-clobbers.explicit-have-precedence]

Explicit register outputs have precedence over the implicit clobbers inserted by `clobber_abi`: a clobber will only be inserted for a register if that register is not used as an output.

[asm.abi-clobbers.supported-abis]

The following ABIs can be used with `clobber_abi`:

Architecture | ABI name | Clobbered registers
--- | --- | ---
x86-32 | `"C"`, `"system"`, `"efiapi"`, `"cdecl"`, `"stdcall"`, `"fastcall"` | `ax`, `cx`, `dx`, `xmm[0-7]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`
x86-64 | `"C"`, `"system"` (on Windows), `"efiapi"`, `"win64"` | `ax`, `cx`, `dx`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]`
x86-64 | `"C"`, `"system"` (on non-Windows), `"sysv64"` | `ax`, `cx`, `dx`, `si`, `di`, `r[8-11]`, `xmm[0-31]`, `mm[0-7]`, `k[0-7]`, `st([0-7])`, `tmm[0-7]`
AArch64 | `"C"`, `"system"`, `"efiapi"` | `x[0-17]`, `x18`*, `x30`, `v[0-31]`, `p[0-15]`, `ffr`
Arm64EC | `"C"`, `"system"` | `x[0-12]`, `x[15-17]`, `x30`, `v[0-15]`
ARM | `"C"`, `"system"`, `"efiapi"`, `"aapcs"` | `r[0-3]`, `r12`, `r14`, `s[0-15]`, `d[0-7]`, `d[16-31]`
RISC-V | `"C"`, `"system"`, `"efiapi"` | `x1`, `x[5-7]`, `x[10-17]`*, `x[28-31]`*, `f[0-7]`, `f[10-17]`, `f[28-31]`, `v[0-31]`
LoongArch | `"C"`, `"system"` | `$r1`, `$r[4-20]`, `$f[0-23]`
s390x | `"C"`, `"system"` | `r[0-5]`, `r14`, `f[0-7]`, `v[0-31]`, `a[2-15]`

> Note

> - On AArch64 `x18` only included in the clobber list if it is not considered as a reserved register on the target.
> - On RISC-V `x[16-17]` and `x[28-31]` only included in the clobber list if they are not considered as reserved registers on the target.

The list of clobbered registers for each ABI is updated in rustc as architectures gain new registers: this ensures that `asm!` clobbers will continue to be correct when LLVM starts using these new registers in its generated code.

[asm.options]

## Options

[asm.options.supported-options]

Flags are used to further influence the behavior of the inline assembly code. Currently the following options are defined:

[asm.options.supported-options.pure]

- `pure`: The assembly code has no side effects, must eventually return, and its outputs depend only on its direct inputs (i.e. the values themselves, not what they point to) or values read from memory (unless the `nomem` options is also set). This allows the compiler to execute the assembly code fewer times than specified in the program (e.g. by hoisting it out of a loop) or even eliminate it entirely if the outputs are not used. The `pure` option must be combined with either the `nomem` or `readonly` options, otherwise a compile-time error is emitted.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i32 = 0;
    let z: i32;
    // pure can be used to optimize by assuming the assembly has no side effects
    unsafe { core::arch::asm!("inc {}", inout(reg) x => z, options(pure, nomem)); }
    assert_eq!(z, 1);
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i32 = 0;
    let z: i32;
    // Either nomem or readonly must be satisfied, to indicate whether or not
    // memory is allowed to be read
    unsafe { core::arch::asm!("inc {}", inout(reg) x => z, options(pure)); }
    // ERROR: the `pure` option must be combined with either `nomem` or `readonly`
    assert_eq!(z, 0);
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.options.supported-options.nomem]

- `nomem`: The assembly code does not read from or write to any memory accessible outside of the assembly code. This allows the compiler to cache the values of modified global variables in registers across execution of the assembly code since it knows that they are not read from or written to by it. The compiler also assumes that the assembly code does not perform any kind of synchronization with other threads, e.g. via fences.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x = 0i32;
    let z: i32;
    // Accessing outside memory from assembly when `nomem` is
    // specified is disallowed
    unsafe {
        core::arch::asm!("mov {val:e}, dword ptr [{ptr}]",
            ptr = in(reg) &mut x,
            val = lateout(reg) z,
            options(nomem)
        )
    }

    // Writing to outside memory from assembly when `nomem` is
    // specified is also undefined behaviour
    unsafe {
        core::arch::asm!("mov  dword ptr [{ptr}], {val:e}",
            ptr = in(reg) &mut x,
            val = in(reg) z,
            options(nomem)
        )
    }
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i32 = 0;
    let z: i32;
    // If we allocate our own memory, such as via `push`, however.
    // we can still use it
    unsafe {
        core::arch::asm!("push {x}", "add qword ptr [rsp], 1", "pop {x}",
            x = inout(reg) x => z,
            options(nomem)
        );
    }
    assert_eq!(z, 1);
    }
    }

[asm.options.supported-options.readonly]

- `readonly`: The assembly code does not write to any memory accessible outside of the assembly code. This allows the compiler to cache the values of unmodified global variables in registers across execution of the assembly code since it knows that they are not written to by it. The compiler also assumes that this assembly code does not perform any kind of synchronization with other threads, e.g. via fences.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let mut x = 0;
    // We cannot modify outside memory when `readonly` is specified
    unsafe {
        core::arch::asm!("mov dword ptr[{}], 1", in(reg) &mut x, options(readonly))
    }
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64 = 0;
    let z: i64;
    // We can still read from it, though
    unsafe {
        core::arch::asm!("mov {x}, qword ptr [{x}]",
            x = inout(reg) &x => z,
            options(readonly)
        );
    }
    assert_eq!(z, 0);
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i64 = 0;
    let z: i64;
    // Same exception applies as with nomem.
    unsafe {
        core::arch::asm!("push {x}", "add qword ptr [rsp], 1", "pop {x}",
            x = inout(reg) x => z,
            options(readonly)
        );
    }
    assert_eq!(z, 1);
    }
    }

[asm.options.supported-options.preserves_flags]

- `preserves_flags`: The assembly code does not modify the flags register (defined in the rules below). This allows the compiler to avoid recomputing the condition flags after execution of the assembly code.

[asm.options.supported-options.noreturn]

- `noreturn`: The assembly code does not fall through; behavior is undefined if it does. It may still jump to `label` blocks. If any `label` blocks return unit, the `asm!` block will return unit. Otherwise it will return `!` (never). As with a call to a function that does not return, local variables in scope are not dropped before execution of the assembly code.

    fn main() -> ! {
    #[cfg(target_arch = "x86_64")] {
        // We can use an instruction to trap execution inside of a noreturn block
        unsafe { core::arch::asm!("ud2", options(noreturn)); }
    }
    #[cfg(not(target_arch = "x86_64"))] panic!("no return");
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // You are responsible for not falling past the end of a noreturn asm block
    unsafe { core::arch::asm!("", options(noreturn)); }
    }
    }

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")]
    let _: () = unsafe {
        // You may still jump to a `label` block
        core::arch::asm!("jmp {}", label {
            println!();
        }, options(noreturn));
    };
    }

[asm.options.supported-options.nostack]

- `nostack`: The assembly code does not push data to the stack, or write to the stack red-zone (if supported by the target). If this option is not used then the stack pointer is guaranteed by the compiler at the start of the assembly code to be suitably aligned (according to the target ABI) for a function call.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // `push` and `pop` are UB when used with nostack
    unsafe { core::arch::asm!("push rax", "pop rax", options(nostack)); }
    }
    }

[asm.options.supported-options.att_syntax]

- `att_syntax`: This option is only valid on x86, and causes the assembler to use the `.att_syntax prefix` mode of the GNU assembler. Register operands are substituted in with a leading `%`.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let x: i32;
    let y = 1i32;
    // We need to use AT&T Syntax here. src, dest order for operands
    unsafe {
        core::arch::asm!("mov {y:e}, {x:e}",
            x = lateout(reg) x,
            y = in(reg) y,
            options(att_syntax)
        );
    }
    assert_eq!(x, y);
    }
    }

[asm.options.supported-options.raw]

- `raw`: This causes the template string to be parsed as a raw assembly string, with no special handling for `{` and `}`. This is primarily useful when including raw assembly code from an external file using `include_str!`.

[asm.options.checks]

The compiler performs some additional checks on options:

[asm.options.checks.mutually-exclusive]

- The `nomem` and `readonly` options are mutually exclusive: it is a compile-time error to specify both.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // nomem is strictly stronger than readonly, they can't be specified together
    unsafe { core::arch::asm!("", options(nomem, readonly)); }
    // ERROR: the `nomem` and `readonly` options are mutually exclusive
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.options.checks.pure]

- It is a compile-time error to specify `pure` on an asm block with no outputs or only discarded outputs (`_`).

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    // pure blocks need at least one output
    unsafe { core::arch::asm!("", options(pure)); }
    // ERROR: asm with the `pure` option must have at least one output
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.options.checks.noreturn]

- It is a compile-time error to specify `noreturn` on an asm block with outputs and without labels.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let z: i32;
    // noreturn can't have outputs
    unsafe { core::arch::asm!("mov {:e}, 1", out(reg) z, options(noreturn)); }
    // ERROR: asm outputs are not allowed with the `noreturn` option
    }
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");
    }

[asm.options.checks.label-with-outputs]

- It is a compile-time error to have any `label` blocks in an asm block with outputs.

[asm.options.naked_asm-restriction]

`naked_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful because the inline assembly defines the whole function body.

[asm.options.global_asm-restriction]

`global_asm!` only supports the `att_syntax` and `raw` options. The remaining options are not meaningful for global-scope inline assembly.

    fn main() {}
    #[cfg(target_arch = "x86_64")]
    // nomem is useless on global_asm!
    core::arch::global_asm!("", options(nomem));
    #[cfg(not(target_arch = "x86_64"))] core::compile_error!("Test not supported on this arch");

[asm.rules]

## Rules for inline assembly

[asm.rules.intro]

To avoid undefined behavior, these rules must be followed when using function-scope inline assembly (`asm!`):

[asm.rules.reg-not-input]

- Any registers not specified as inputs will contain an undefined value on entry to the assembly code.
  - An “undefined value” in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).

[asm.rules.reg-not-output]

- Any registers not specified as outputs must have the same value upon exiting the assembly code as they had on entry, otherwise behavior is undefined.
  - This only applies to registers which can be specified as an input or output. Other registers follow target-specific rules.
  - Note that a `lateout` may be allocated to the same register as an `in`, in which case this rule does not apply. Code should not rely on this however since it depends on the results of register allocation.

[asm.rules.unwind]

- Behavior is undefined if execution unwinds out of the assembly code.
  - This also applies if the assembly code calls a function which then unwinds.

[asm.rules.mem-same-as-ffi]

- The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function.
  - If the `readonly` option is set, then only memory reads are allowed.
  - If the `nomem` option is set then no reads or writes to memory are allowed.
  - These rules do not apply to memory which is private to the assembly code, such as stack space allocated within it.

[asm.rules.black-box]

- The compiler cannot assume that the instructions in the assembly code are the ones that will actually end up executed.
  - This effectively means that the compiler must treat the assembly code as a black box and only take the interface specification into account, not the instructions themselves.
  - Runtime code patching is allowed, via target-specific mechanisms.
  - However there is no guarantee that each block of assembly code in the source directly corresponds to a single instance of instructions in the object file; the compiler is free to duplicate or deduplicate the assembly code in `asm!` blocks.

[asm.rules.stack-below-sp]

- Unless the `nostack` option is set, assembly code is allowed to use stack space below the stack pointer.
  - On entry to the assembly code the stack pointer is guaranteed to be suitably aligned (according to the target ABI) for a function call.
  - You are responsible for making sure you don’t overflow the stack (e.g. use stack probing to ensure you hit a guard page).
  - You should adjust the stack pointer when allocating stack memory as required by the target ABI.
  - The stack pointer must be restored to its original value before leaving the assembly code.

[asm.rules.noreturn]

- If the `noreturn` option is set then behavior is undefined if execution falls through the end of the assembly code.

[asm.rules.pure]

- If the `pure` option is set then behavior is undefined if the `asm!` has side-effects other than its direct outputs. Behavior is also undefined if two executions of the `asm!` code with the same inputs result in different outputs.
  - When used with the `nomem` option, “inputs” are just the direct inputs of the `asm!`.
  - When used with the `readonly` option, “inputs” comprise the direct inputs of the assembly code and any memory that it is allowed to read.

[asm.rules.preserved-registers]

- These flags registers must be restored upon exiting the assembly code if the `preserves_flags` option is set:
  - x86
    - Status flags in `EFLAGS` (CF, PF, AF, ZF, SF, OF).
    - Floating-point status word (all).
    - Floating-point exception flags in `MXCSR` (PE, UE, OE, ZE, DE, IE).
  - ARM
    - Condition flags in `CPSR` (N, Z, C, V)
    - Saturation flag in `CPSR` (Q)
    - Greater than or equal flags in `CPSR` (GE).
    - Condition flags in `FPSCR` (N, Z, C, V)
    - Saturation flag in `FPSCR` (QC)
    - Floating-point exception flags in `FPSCR` (IDC, IXC, UFC, OFC, DZC, IOC).
  - AArch64 and Arm64EC
    - Condition flags (`NZCV` register).
    - Floating-point status (`FPSR` register).
  - RISC-V
    - Floating-point exception flags in `fcsr` (`fflags`).
    - Vector extension state (`vtype`, `vl`, `vxsat`, and `vxrm`).
  - LoongArch
    - Floating-point condition flags in `$fcc[0-7]`.
  - s390x
    - The condition code register `cc`.

[asm.rules.x86-df]

- On x86, the direction flag (DF in `EFLAGS`) is clear on entry to the assembly code and must be clear on exit.
  - Behavior is undefined if the direction flag is set on exiting the assembly code.

[asm.rules.x86-x87]

- On x86, the x87 floating-point register stack must remain unchanged unless all of the `st([0-7])` registers have been marked as clobbered with `out("st(0)") _, out("st(1)") _, ...`.
  - If all x87 registers are clobbered then the x87 register stack is guaranteed to be empty upon entering the assembly code. Assembly code must ensure that the x87 register stack is also empty when exiting the assembly code.

    #[cfg(target_arch = "x86_64")]
    pub fn fadd(x: f64, y: f64) -> f64 {
      let mut out = 0f64;
      let mut top = 0u16;
      // we can do complex stuff with x87 if we clobber the entire x87 stack
      unsafe { core::arch::asm!(
        "fld qword ptr [{x}]",
        "fld qword ptr [{y}])",
        "faddp",
        "fstp qword ptr [{out}]",
        "xor eax, eax",
        "fstsw ax",
        "shl eax, 11",
        x = in(reg) &x,
        y = in(reg) &y,
        out = in(reg) &mut out,
        out("st(0)") _, out("st(1)") _, out("st(2)") _, out("st(3)") _,
        out("st(4)") _, out("st(5)") _, out("st(6)") _, out("st(7)") _,
        out("eax") top
      );}

      assert_eq!(top & 0x7, 0);
      out
    }

    pub fn main() {
    #[cfg(target_arch = "x86_64")]{
      assert_eq!(fadd(1.0, 1.0), 2.0);
    }
    }

[asm.rules.arm64ec]

- On arm64ec, call checkers with appropriate thunks are mandatory when calling functions.

[asm.rules.only-on-exit]

- The requirement of restoring the stack pointer and non-output registers to their original value only applies when exiting the assembly code.
  - This means that assembly code that does not fall through and does not jump to any `label` blocks, even if not marked `noreturn`, doesn’t need to preserve these registers.
  - When returning to the assembly code of a different `asm!` block than you entered (e.g. for context switching), these registers must contain the value they had upon entering the `asm!` block that you are exiting.
    - You cannot exit the assembly code of an `asm!` block that has not been entered. Neither can you exit the assembly code of an `asm!` block whose assembly code has already been exited (without first entering it again).
    - You are responsible for switching any target-specific state (e.g. thread-local storage, stack bounds).
    - You cannot jump from an address in one `asm!` block to an address in another, even within the same function or block, without treating their contexts as potentially different and requiring context switching. You cannot assume that any particular value in those contexts (e.g. current stack pointer or temporary values below the stack pointer) will remain unchanged between the two `asm!` blocks.
    - The set of memory locations that you may access is the intersection of those allowed by the `asm!` blocks you entered and exited.

[asm.rules.not-successive]

- You cannot assume that two `asm!` blocks adjacent in source code, even without any other code between them, will end up in successive addresses in the binary without any other instructions between them.

[asm.rules.not-exactly-once]

- You cannot assume that an `asm!` block will appear exactly once in the output binary. The compiler is allowed to instantiate multiple copies of the `asm!` block, for example when the function containing it is inlined in multiple places.

[asm.rules.x86-prefix-restriction]

- On x86, inline assembly must not end with an instruction prefix (such as `LOCK`) that would apply to instructions generated by the compiler.
  - The compiler is currently unable to detect this due to the way inline assembly is compiled, but may catch and reject this in the future.

[asm.rules.preserves_flags]

> Note

> As a general rule, the flags covered by `preserves_flags` are those which are not preserved when performing a function call.

[asm.naked-rules]

## Rules for naked inline assembly

[asm.naked-rules.intro]

To avoid undefined behavior, these rules must be followed when using function-scope inline assembly in naked functions (`naked_asm!`):

[asm.naked-rules.reg-not-input]

- Any registers not used for function inputs according to the calling convention and function signature will contain an undefined value on entry to the `naked_asm!` block.
  - An “undefined value” in the context of inline assembly means that the register can (non-deterministically) have any one of the possible values allowed by the architecture. Notably it is not the same as an LLVM `undef` which can have a different value every time you read it (since such a concept does not exist in assembly code).

[asm.naked-rules.callee-saved-registers]

- All callee-saved registers must have the same value upon return as they had on entry.

[asm.naked-rules.caller-saved-registers]

- Caller-saved registers may be used freely.

[asm.naked-rules.noreturn]

- Behavior is undefined if execution falls through past the end of the assembly code.
  - Every path through the assembly code is expected to terminate with a return instruction or to diverge.

[asm.naked-rules.mem-same-as-ffi]

- The set of memory locations that assembly code is allowed to read and write are the same as those allowed for an FFI function.

[asm.naked-rules.black-box]

- The compiler cannot assume that the instructions in the `naked_asm!` block are the ones that will actually be executed.
  - This effectively means that the compiler must treat the `naked_asm!` as a black box and only take the interface specification into account, not the instructions themselves.
  - Runtime code patching is allowed, via target-specific mechanisms.

[asm.naked-rules.unwind]

- Unwinding out of a `naked_asm!` block is allowed.
  - For correct behavior, the appropriate assembler directives that emit unwinding metadata must be used.

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    #[unsafe(naked)]
    extern "sysv64-unwind" fn unwinding_naked() {
        core::arch::naked_asm!(
            // "CFI" here stands for "call frame information".
            ".cfi_startproc",
            // The CFA (canonical frame address) is the value of `rsp`
            // before the `call`, i.e. before the return address, `rip`,
            // was pushed to `rsp`, so it's eight bytes higher in memory
            // than `rsp` upon function entry (after `rip` has been
            // pushed).
            //
            // This is the default, so we don't have to write it.
            //".cfi_def_cfa rsp, 8",
            //
            // The traditional thing to do is to preserve the base
            // pointer, so we'll do that.
            "push rbp",
            // Since we've now extended the stack downward by 8 bytes in
            // memory, we need to adjust the offset to the CFA from `rsp`
            // by another 8 bytes.
            ".cfi_adjust_cfa_offset 8",
            // We also then annotate where we've stored the caller's value
            // of `rbp`, relative to the CFA, so that when unwinding into
            // the caller we can find it, in case we need it to calculate
            // the caller's CFA relative to it.
            //
            // Here, we've stored the caller's `rbp` starting 16 bytes
            // below the CFA.  I.e., starting from the CFA, there's first
            // the `rip` (which starts 8 bytes below the CFA and continues
            // up to it), then there's the caller's `rbp` that we just
            // pushed.
            ".cfi_offset rbp, -16",
            // As is traditional, we set the base pointer to the value of
            // the stack pointer.  This way, the base pointer stays the
            // same throughout the function body.
            "mov rbp, rsp",
            // We can now track the offset to the CFA from the base
            // pointer.  This means we don't need to make any further
            // adjustments until the end, as we don't change `rbp`.
            ".cfi_def_cfa_register rbp",
            // We can now call a function that may panic.
            "call {f}",
            // Upon return, we restore `rbp` in preparation for returning
            // ourselves.
            "pop rbp",
            // Now that we've restored `rbp`, we must specify the offset
            // to the CFA again in terms of `rsp`.
            ".cfi_def_cfa rsp, 8",
            // Now we can return.
            "ret",
            ".cfi_endproc",
            f = sym may_panic,
        )
    }

    extern "sysv64-unwind" fn may_panic() {
        panic!("unwind");
    }
    }
    }

> Note

> For more information on the `cfi` assembler directives above, see these resources:

> - Using `as` - CFI directives
> - DWARF Debugging Information Format Version 5
> - ImperialViolet - CFI directives in assembly files

[asm.validity]

### Correctness and validity

[asm.validity.necessary-but-not-sufficient]

In addition to all of the previous rules, the string argument to `asm!` must ultimately become— after all other arguments are evaluated, formatting is performed, and operands are translated— assembly that is both syntactically correct and semantically valid for the target architecture. The formatting rules allow the compiler to generate assembly with correct syntax. Rules concerning operands permit valid translation of Rust operands into and out of the assembly code. Adherence to these rules is necessary, but not sufficient, for the final expanded assembly to be both correct and valid. For instance:

- arguments may be placed in positions which are syntactically incorrect after formatting
- an instruction may be correctly written, but given architecturally invalid operands
- an architecturally unspecified instruction may be assembled into unspecified code
- a set of instructions, each correct and valid, may cause undefined behavior if placed in immediate succession

[asm.validity.non-exhaustive]

As a result, these rules are non-exhaustive. The compiler is not required to check the correctness and validity of the initial string nor the final assembly that is generated. The assembler may check for correctness and validity but is not required to do so. When using `asm!`, a typographical error may be sufficient to make a program unsound, and the rules for assembly may include thousands of pages of architectural reference manuals. Programmers should exercise appropriate care, as invoking this `unsafe` capability comes with assuming the responsibility of not violating rules of both the compiler or the architecture.

[asm.directives]

### Directives support

[asm.directives.subset-supported]

Inline assembly supports a subset of the directives supported by both GNU AS and LLVM’s internal assembler, given as follows. The result of using other directives is assembler-specific (and may cause an error, or may be accepted as-is).

[asm.directives.stateful]

If inline assembly includes any “stateful” directive that modifies how subsequent assembly is processed, the assembly code must undo the effects of any such directives before the inline assembly ends.

[asm.directives.supported-directives]

The following directives are guaranteed to be supported by the assembler:

- `.2byte`
- `.4byte`
- `.8byte`
- `.align`
- `.alt_entry`
- `.ascii`
- `.asciz`
- `.balign`
- `.balignl`
- `.balignw`
- `.bss`
- `.byte`
- `.comm`
- `.data`
- `.def`
- `.double`
- `.endef`
- `.equ`
- `.equiv`
- `.eqv`
- `.fill`
- `.float`
- `.global`
- `.globl`
- `.inst`
- `.insn`
- `.lcomm`
- `.long`
- `.octa`
- `.option`
- `.p2align`
- `.popsection`
- `.private_extern`
- `.pushsection`
- `.quad`
- `.scl`
- `.section`
- `.set`
- `.short`
- `.size`
- `.skip`
- `.sleb128`
- `.space`
- `.string`
- `.text`
- `.type`
- `.uleb128`
- `.word`

    #![allow(unused)]
    fn main() {
    #[cfg(target_arch = "x86_64")] {
    let bytes: *const u8;
    let len: usize;
    unsafe {
        core::arch::asm!(
            "jmp 3f", "2: .ascii \"Hello World!\"",
            "3: lea {bytes}, [2b+rip]",
            "mov {len}, 12",
            bytes = out(reg) bytes,
            len = out(reg) len
        );
    }

    let s = unsafe { core::str::from_utf8_unchecked(core::slice::from_raw_parts(bytes, len)) };

    assert_eq!(s, "Hello World!");
    }
    }

[asm.target-specific-directives]

#### Target specific directive support

[asm.target-specific-directives.dwarf-unwinding]

##### Dwarf unwinding

The following directives are supported on ELF targets that support DWARF unwind info:

- `.cfi_adjust_cfa_offset`
- `.cfi_def_cfa`
- `.cfi_def_cfa_offset`
- `.cfi_def_cfa_register`
- `.cfi_endproc`
- `.cfi_escape`
- `.cfi_lsda`
- `.cfi_offset`
- `.cfi_personality`
- `.cfi_register`
- `.cfi_rel_offset`
- `.cfi_remember_state`
- `.cfi_restore`
- `.cfi_restore_state`
- `.cfi_return_column`
- `.cfi_same_value`
- `.cfi_sections`
- `.cfi_signal_frame`
- `.cfi_startproc`
- `.cfi_undefined`
- `.cfi_window_save`

[asm.target-specific-directives.structured-exception-handling]

##### Structured exception handling

On targets with structured exception Handling, the following additional directives are guaranteed to be supported:

- `.seh_endproc`
- `.seh_endprologue`
- `.seh_proc`
- `.seh_pushreg`
- `.seh_savereg`
- `.seh_setframe`
- `.seh_stackalloc`

[asm.target-specific-directives.x86]

##### x86 (32-bit and 64-bit)

On x86 targets, both 32-bit and 64-bit, the following additional directives are guaranteed to be supported:

- `.nops`
- `.code16`
- `.code32`
- `.code64`

Use of `.code16`, `.code32`, and `.code64` directives are only supported if the state is reset to the default before exiting the assembly code. 32-bit x86 uses `.code32` by default, and x86_64 uses `.code64` by default.

[asm.target-specific-directives.arm-32-bit]

##### ARM (32-bit)

On ARM, the following additional directives are guaranteed to be supported:

- `.even`
- `.fnstart`
- `.fnend`
- `.save`
- `.movsp`
- `.code`
- `.thumb`
- `.thumb_func`

[safety]

# Unsafety

[safety.intro]

Unsafe operations are those that can potentially violate the memory-safety guarantees of Rust’s static semantics.

[safety.unsafe-ops]

The following language level features cannot be used in the safe subset of Rust:

[safety.unsafe-deref]

- Dereferencing a raw pointer.

[safety.unsafe-static]

- Reading or writing a mutable or unsafe external static variable.

[safety.unsafe-union-access]

- Accessing a field of a `union`, other than to assign to it.

[safety.unsafe-call]

- Calling an unsafe function.

[safety.unsafe-target-feature-call]

- Calling a safe function marked with a `target_feature` from a function that does not have a `target_feature` attribute enabling the same features (see attributes.codegen.target_feature.safety-restrictions).

[safety.unsafe-impl]

- Implementing an unsafe trait.

[safety.unsafe-extern]

- Declaring an `extern` block1.

[safety.unsafe-attribute]

- Applying an unsafe attribute to an item.

1. Prior to the 2024 edition, extern blocks were allowed to be declared without `unsafe`. ↩

[unsafe]

# The `unsafe` keyword

[unsafe.intro]

The `unsafe` keyword is used to create or discharge the obligation to prove something safe. Specifically:

- It is used to mark code that defines extra safety conditions that must be upheld elsewhere.
  - This includes `unsafe fn`, `unsafe static`, and `unsafe trait`.
- It is used to mark code that the programmer asserts satisfies safety conditions defined elsewhere.
  - This includes `unsafe {}`, `unsafe impl`, `unsafe fn` without `unsafe_op_in_unsafe_fn`, `unsafe extern`, and `#[unsafe(attr)]`.

The following discusses each of these cases. See the keyword documentation for some illustrative examples.

[unsafe.positions]

The `unsafe` keyword can occur in several different contexts:

- unsafe functions (`unsafe fn`)
- unsafe blocks (`unsafe {}`)
- unsafe traits (`unsafe trait`)
- unsafe trait implementations (`unsafe impl`)
- unsafe external blocks (`unsafe extern`)
- unsafe external statics (`unsafe static`)
- unsafe attributes (`#[unsafe(attr)]`)

[unsafe.fn]

## Unsafe functions (`unsafe fn`)

[unsafe.fn.intro]

Unsafe functions are functions that are not safe in all contexts and/or for all possible inputs. We say they have extra safety conditions, which are requirements that must be upheld by all callers and that the compiler does not check. For example, `get_unchecked` has the extra safety condition that the index must be in-bounds. The unsafe function should come with documentation explaining what those extra safety conditions are.

[unsafe.fn.safety]

Such a function must be prefixed with the keyword `unsafe` and can only be called from inside an `unsafe` block, or inside `unsafe fn` without the `unsafe_op_in_unsafe_fn` lint.

[unsafe.block]

## Unsafe blocks (`unsafe {}`)

[unsafe.block.intro]

A block of code can be prefixed with the `unsafe` keyword to permit using the unsafe actions as defined in the Unsafety chapter, such as calling other unsafe functions or dereferencing raw pointers.

[unsafe.block.fn-body]

By default, the body of an unsafe function is also considered to be an unsafe block; this can be changed by enabling the `unsafe_op_in_unsafe_fn` lint.

By putting operations into an unsafe block, the programmer states that they have taken care of satisfying the extra safety conditions of all operations inside that block.

Unsafe blocks are the logical dual to unsafe functions: where unsafe functions define a proof obligation that callers must uphold, unsafe blocks state that all relevant proof obligations of functions or operations called inside the block have been discharged. There are many ways to discharge proof obligations; for example, there could be run-time checks or data structure invariants that guarantee that certain properties are definitely true, or the unsafe block could be inside an `unsafe fn`, in which case the block can use the proof obligations of that function to discharge the proof obligations arising inside the block.

Unsafe blocks are used to wrap foreign libraries, make direct use of hardware or implement features not directly present in the language. For example, Rust provides the language features necessary to implement memory-safe concurrency in the language but the implementation of threads and message passing in the standard library uses unsafe blocks.

Rust’s type system is a conservative approximation of the dynamic safety requirements, so in some cases there is a performance cost to using safe code. For example, a doubly-linked list is not a tree structure and can only be represented with reference-counted pointers in safe code. By using `unsafe` blocks to represent the reverse links as raw pointers, it can be implemented without reference counting. (See “Learn Rust With Entirely Too Many Linked Lists” for a more in-depth exploration of this particular example.)

[unsafe.trait]

## Unsafe traits (`unsafe trait`)

[unsafe.trait.intro]

An unsafe trait is a trait that comes with extra safety conditions that must be upheld by implementations of the trait. The unsafe trait should come with documentation explaining what those extra safety conditions are.

[unsafe.trait.safety]

Such a trait must be prefixed with the keyword `unsafe` and can only be implemented by `unsafe impl` blocks.

[unsafe.impl]

## Unsafe trait implementations (`unsafe impl`)

When implementing an unsafe trait, the implementation needs to be prefixed with the `unsafe` keyword. By writing `unsafe impl`, the programmer states that they have taken care of satisfying the extra safety conditions required by the trait.

Unsafe trait implementations are the logical dual to unsafe traits: where unsafe traits define a proof obligation that implementations must uphold, unsafe implementations state that all relevant proof obligations have been discharged.

[unsafe.extern]

## Unsafe external blocks (`unsafe extern`)

The programmer who declares an external block must assure that the signatures of the items contained within are correct. Failing to do so may lead to undefined behavior. That this obligation has been met is indicated by writing `unsafe extern`.

[unsafe.extern.edition2024]

> 2024 Edition differences

> Prior to edition 2024, `extern` blocks were allowed without being qualified as `unsafe`.

[unsafe.attribute]

## Unsafe attributes (`#[unsafe(attr)]`)

An unsafe attribute is one that has extra safety conditions that must be upheld when using the attribute. The compiler cannot check whether these conditions have been upheld. To assert that they have been, these attributes must be wrapped in `unsafe(..)`, e.g. `#[unsafe(no_mangle)]`.

[undefined]

# Behavior considered undefined

[undefined.general]

Rust code is incorrect if it exhibits any of the behaviors in the following list. This includes code within `unsafe` blocks and `unsafe` functions. `unsafe` only means that avoiding undefined behavior is on the programmer; it does not change anything about the fact that Rust programs must never cause undefined behavior.

[undefined.soundness]

It is the programmer’s responsibility when writing `unsafe` code to ensure that any safe code interacting with the `unsafe` code cannot trigger these behaviors. `unsafe` code that satisfies this property for any safe client is called sound; if `unsafe` code can be misused by safe code to exhibit undefined behavior, it is unsound.

> Warning

> The following list is not exhaustive; it may grow or shrink. There is no formal model of Rust’s semantics for what is and is not allowed in unsafe code, so there may be more behavior considered unsafe. We also reserve the right to make some of the behavior in that list defined in the future. In other words, this list does not say that anything will definitely always be undefined in all future Rust version (but we might make such commitments for some list items in the future).

> Please read the Rustonomicon before writing unsafe code.

[undefined.race]

- Data races.

[undefined.pointer-access]

- Accessing (loading from or storing to) a place that is dangling or based on a misaligned pointer.

[undefined.place-projection]

- Performing a place projection that violates the requirements of in-bounds pointer arithmetic. A place projection is a field expression, a tuple index expression, or an array/slice index expression.

[undefined.alias]

- Breaking the pointer aliasing rules. The exact aliasing rules are not determined yet, but here is an outline of the general principles: `&T` must point to memory that is not mutated while they are live (except for data inside an `UnsafeCell<U>`), and `&mut T` must point to memory that is not read or written by any pointer not derived from the reference and that no other reference points to while they are live. `Box<T>` is treated similar to `&'static mut T` for the purpose of these rules. The exact liveness duration is not specified, but some bounds exist:

  - For references, the liveness duration is upper-bounded by the syntactic lifetime assigned by the borrow checker; it cannot be live any longer than that lifetime.
  - Each time a reference or box is dereferenced or reborrowed, it is considered live.
  - Each time a reference or box is passed to or returned from a function, it is considered live.
  - When a reference (but not a `Box`!) is passed to a function, it is live at least as long as that function call, again except if the `&T` contains an `UnsafeCell<U>`.

  All this also applies when values of these types are passed in a (nested) field of a compound type, but not behind pointer indirections.

[undefined.immutable]

- Mutating immutable bytes. All bytes reachable through a const-promoted expression are immutable, as well as bytes reachable through borrows in `static` and `const` initializers that have been lifetime-extended to `'static`. The bytes owned by an immutable binding or immutable `static` are immutable, unless those bytes are part of an `UnsafeCell<U>`.

  Moreover, the bytes pointed to by a shared reference, including transitively through other references (both shared and mutable) and `Box`es, are immutable; transitivity includes those references stored in fields of compound types.

  A mutation is any write of more than 0 bytes which overlaps with any of the relevant bytes (even if that write does not change the memory contents).

[undefined.intrinsic]

- Invoking undefined behavior via compiler intrinsics.

[undefined.target-feature]

- Executing code compiled with platform features that the current platform does not support (see `target_feature`), except if the platform explicitly documents this to be safe.

[undefined.call]

- Calling a function with the wrong call ABI, or unwinding past a stack frame that does not allow unwinding (e.g. by calling a `"C-unwind"` function imported or transmuted as a `"C"` function or function pointer).

[undefined.invalid]

- Producing an invalid value. “Producing” a value happens any time a value is assigned to or read from a place, passed to a function/primitive operation or returned from a function/primitive operation.

[undefined.asm]

- Incorrect use of inline assembly. For more details, refer to the rules to follow when writing code that uses inline assembly.

[undefined.runtime]

- Violating assumptions of the Rust runtime. Most assumptions of the Rust runtime are currently not explicitly documented.
  - For assumptions specifically related to unwinding, see the panic documentation.
  - The runtime assumes that a Rust stack frame is not deallocated without executing destructors for local variables owned by the stack frame. This assumption can be violated by C functions like `longjmp`.

> Note

> Undefined behavior affects the entire program. For example, calling a function in C that exhibits undefined behavior of C means your entire program contains undefined behaviour that can also affect the Rust code. And vice versa, undefined behavior in Rust can cause adverse affects on code executed by any FFI calls to other languages.

[undefined.pointed-to]

## Pointed-to bytes

The span of bytes a pointer or reference “points to” is determined by the pointer value and the size of the pointee type (using `size_of_val`).

[undefined.misaligned]

## Places based on misaligned pointers

[undefined.misaligned.general]

A place is said to be “based on a misaligned pointer” if the last `*` projection during place computation was performed on a pointer that was not aligned for its type. (If there is no `*` projection in the place expression, then this is accessing the field of a local or `static` and rustc will guarantee proper alignment. If there are multiple `*` projection, then each of them incurs a load of the pointer-to-be-dereferenced itself from memory, and each of these loads is subject to the alignment constraint. Note that some `*` projections can be omitted in surface Rust syntax due to automatic dereferencing; we are considering the fully expanded place expression here.)

For instance, if `ptr` has type `*const S` where `S` has an alignment of 8, then `ptr` must be 8-aligned or else `(*ptr).f` is “based on an misaligned pointer”. This is true even if the type of the field `f` is `u8` (i.e., a type with alignment 1). In other words, the alignment requirement derives from the type of the pointer that was dereferenced, not the type of the field that is being accessed.

[undefined.misaligned.load-store]

Note that a place based on a misaligned pointer only leads to undefined behavior when it is loaded from or stored to.

[undefined.misaligned.raw]

`&raw const`/`&raw mut` on such a place is allowed.

[undefined.misaligned.reference]

`&`/`&mut` on a place requires the alignment of the field type (or else the program would be “producing an invalid value”), which generally is a less restrictive requirement than being based on an aligned pointer.

[undefined.misaligned.packed]

Taking a reference will lead to a compiler error in cases where the field type might be more aligned than the type that contains it, i.e., `repr(packed)`. This means that being based on an aligned pointer is always sufficient to ensure that the new reference is aligned, but it is not always necessary.

[undefined.dangling]

## Dangling pointers

[undefined.dangling.general]

A reference/pointer is “dangling” if not all of the bytes it points to are part of the same live allocation (so in particular they all have to be part of some allocation).

[undefined.dangling.zero-size]

If the size is 0, then the pointer is trivially never “dangling” (even if it is a null pointer).

[undefined.dangling.dynamic-size]

Note that dynamically sized types (such as slices and strings) point to their entire range, so it is important that the length metadata is never too large.

[undefined.dangling.alloc-limit]

In particular, the dynamic size of a Rust value (as determined by `size_of_val`) must never exceed `isize::MAX`, since it is impossible for a single allocation to be larger than `isize::MAX`.

[undefined.validity]

## Invalid values

[undefined.validity.general]

The Rust compiler assumes that all values produced during program execution are “valid”, and producing an invalid value is hence immediate UB.

Whether a value is valid depends on the type:

[undefined.validity.bool]

- A `bool` value must be `false` (`0`) or `true` (`1`).

[undefined.validity.fn-pointer]

- A `fn` pointer value must be non-null.

[undefined.validity.char]

- A `char` value must not be a surrogate (i.e., must not be in the range `0xD800..=0xDFFF`) and must be equal to or less than `char::MAX`.

[undefined.validity.never]

- A `!` value must never exist.

[undefined.validity.scalar]

- An integer (`i*`/`u*`), floating point value (`f*`), or raw pointer must be initialized, i.e., must not be obtained from uninitialized memory.

[undefined.validity.str]

- A `str` value is treated like `[u8]`, i.e. it must be initialized.

[undefined.validity.enum]

- An `enum` must have a valid discriminant, and all fields of the variant indicated by that discriminant must be valid at their respective type.

[undefined.validity.struct]

- A `struct`, tuple, and array requires all fields/elements to be valid at their respective type.

[undefined.validity.union]

- For a `union`, the exact validity requirements are not decided yet. Obviously, all values that can be created entirely in safe code are valid. If the union has a zero-sized field, then every possible value is valid. Further details are still being debated.

[undefined.validity.reference-box]

- A reference or `Box<T>` must be aligned and non-null, it cannot be dangling, and it must point to a valid value (in case of dynamically sized types, using the actual dynamic type of the pointee as determined by the metadata). Note that the last point (about pointing to a valid value) remains a subject of some debate.

[undefined.validity.wide]

- The metadata of a wide reference, `Box<T>`, or raw pointer must match the type of the unsized tail:
  - `dyn Trait` metadata must be a pointer to a compiler-generated vtable for `Trait`. (For raw pointers, this requirement remains a subject of some debate.)
  - Slice (`[T]`) metadata must be a valid `usize`. Furthermore, for wide references and `Box<T>`, slice metadata is invalid if it makes the total size of the pointed-to value bigger than `isize::MAX`.

[undefined.validity.valid-range]

- If a type has a custom range of a valid values, then a valid value must be in that range. In the standard library, this affects `NonNull<T>` and `NonZero<T>`.

  > Note

  > `rustc` achieves this with the unstable `rustc_layout_scalar_valid_range_*` attributes.

[undefined.validity.const-provenance]

- In const contexts: In addition to what is described above, further provenance-related requirements apply during const evaluation. Any value that holds pure integer data (the `i*`/`u*`/`f*` types as well as `bool` and `char`, enum discriminants, and slice metadata) must not carry any provenance. Any value that holds pointer data (references, raw pointers, function pointers, and `dyn Trait` metadata) must either carry no provenance, or all bytes must be fragments of the same original pointer value in the correct order.

  This implies that transmuting or otherwise reinterpreting a pointer (reference, raw pointer, or function pointer) into a non-pointer type (such as integers) is undefined behavior if the pointer had provenance.

  > Example

  > All of the following are UB:

  >     #![allow(unused)]
  >     fn main() {
  >     use core::mem::MaybeUninit;
  >     use core::ptr;
  >     // We cannot reinterpret a pointer with provenance as an integer,
  >     // as then the bytes of the integer will have provenance.
  >     const _: usize = {
  >         let ptr = &0;
  >         unsafe { (&raw const ptr as *const usize).read() }
  >     };

  >     // We cannot rearrange the bytes of a pointer with provenance and
  >     // then interpret them as a reference, as then a value holding
  >     // pointer data will have pointer fragments in the wrong order.
  >     const _: &i32 = {
  >         let mut ptr = &0;
  >         let ptr_bytes = &raw mut ptr as *mut MaybeUninit::<u8>;
  >         unsafe { ptr::swap(ptr_bytes.add(1), ptr_bytes.add(2)) };
  >         ptr
  >     };
  >     }

[undefined.validity.undef]

Note: Uninitialized memory is also implicitly invalid for any type that has a restricted set of valid values. In other words, the only cases in which reading uninitialized memory is permitted are inside `union`s and in “padding” (the gaps between the fields of a type).

# Behavior not considered `unsafe`

The Rust compiler does not consider the following behaviors unsafe, though a programmer may (should) find them undesirable, unexpected, or erroneous.

- Deadlocks
- Leaks of memory and other resources
- Exiting without calling destructors
- Exposing randomized base addresses through pointer leaks

## Integer overflow

If a program contains arithmetic overflow, the programmer has made an error. In the following discussion, we maintain a distinction between arithmetic overflow and wrapping arithmetic. The first is erroneous, while the second is intentional.

When the programmer has enabled `debug_assert!` assertions (for example, by enabling a non-optimized build), implementations must insert dynamic checks that `panic` on overflow. Other kinds of builds may result in `panics` or silently wrapped values on overflow, at the implementation’s discretion.

In the case of implicitly-wrapped overflow, implementations must provide well-defined (even if still considered erroneous) results by using two’s complement overflow conventions.

The integral types provide inherent methods to allow programmers explicitly to perform wrapping arithmetic. For example, `i32::wrapping_add` provides two’s complement, wrapping addition.

The standard library also provides a `Wrapping<T>` newtype which ensures all standard arithmetic operations for `T` have wrapping semantics.

See RFC 560 for error conditions, rationale, and more details about integer overflow.

## Logic errors

Safe code may impose extra logical constraints that can be checked at neither compile-time nor runtime. If a program breaks such a constraint, the behavior may be unspecified but will not result in undefined behavior. This could include panics, incorrect results, aborts, and non-termination. The behavior may also differ between runs, builds, or kinds of build.

For example, implementing both `Hash` and `Eq` requires that values considered equal have equal hashes. Another example are data structures like `BinaryHeap`, `BTreeMap`, `BTreeSet`, `HashMap` and `HashSet` which describe constraints on the modification of their keys while they are in the data structure. Violating such constraints is not considered unsafe, yet the program is considered erroneous and its behavior unpredictable.

[const-eval]

# Constant evaluation

[const-eval.general]

Constant evaluation is the process of computing the result of expressions during compilation. Only a subset of all expressions can be evaluated at compile-time.

[const-eval.const-expr]

## Constant expressions

[const-eval.const-expr.general]

Certain forms of expressions, called constant expressions, can be evaluated at compile time.

[const-eval.const-expr.const-context]

Expressions in a const context must be constant expressions.

[const-eval.const-expr.evaluation]

Expressions in const contexts are always evaluated at compile time.

[const-eval.const-expr.runtime-context]

Outside of const contexts, constant expressions may be, but are not guaranteed to be, evaluated at compile time.

[const-eval.const-expr.error]

Behaviors such as out of bounds array indexing or overflow are compiler errors if the value must be evaluated at compile time (i.e. in const contexts). Otherwise, these behaviors are warnings, but will likely panic at run-time.

[const-eval.const-expr.list]

The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any `Drop::drop` calls to be run.

[const-eval.const-expr.literal]

- Literals.

[const-eval.const-expr.parameter]

- Const parameters.

[const-eval.const-expr.path-item]

- Paths to functions and constants. Recursively defining constants is not allowed.

[const-eval.const-expr.path-static]

- Paths to statics with these restrictions:

  - Writes to `static` items are not allowed in any constant evaluation context.
  - Reads from `extern` statics are not allowed in any constant evaluation context.
  - If the evaluation is not carried out in an initializer of a `static` item, then reads from any mutable `static` are not allowed. A mutable `static` is a `static mut` item, or a `static` item with an interior-mutable type.

  These requirements are checked only when the constant is evaluated. In other words, having such accesses syntactically occur in const contexts is allowed as long as they never get executed.

[const-eval.const-expr.tuple]

- Tuple expressions.

[const-eval.const-expr.array]

- Array expressions.

[const-eval.const-expr.constructor]

- Struct expressions.

[const-eval.const-expr.block]

- Block expressions, including `unsafe` and `const` blocks.
  - let statements and thus irrefutable patterns, including mutable bindings
  - assignment expressions
  - compound assignment expressions
  - expression statements

[const-eval.const-expr.field]

- Field expressions.

[const-eval.const-expr.index]

- Index expressions, array indexing or slice with a `usize`.

[const-eval.const-expr.range]

- Range expressions.

[const-eval.const-expr.closure]

- Closure expressions which don’t capture variables from the environment.

[const-eval.const-expr.builtin-arith-logic]

- Built-in negation, arithmetic, logical, comparison or lazy boolean operators used on integer and floating point types, `bool`, and `char`.

[const-eval.const-expr.borrows]

- All forms of borrows, including raw borrows, except borrows of expressions whose temporary scopes would be extended (see temporary lifetime extension) to the end of the program and which are either:

  - Mutable borrows.
  - Shared borrows of expressions that result in values with interior mutability.

      #![allow(unused)]
      fn main() {
      // Due to being in tail position, this borrow extends the scope of the
      // temporary to the end of the program. Since the borrow is mutable,
      // this is not allowed in a const expression.
      const C: &u8 = &mut 0; // ERROR not allowed
      }

      #![allow(unused)]
      fn main() {
      // Const blocks are similar to initializers of `const` items.
      let _: &u8 = const { &mut 0 }; // ERROR not allowed
      }

      #![allow(unused)]
      fn main() {
      use core::sync::atomic::AtomicU8;
      // This is not allowed as 1) the temporary scope is extended to the
      // end of the program and 2) the temporary has interior mutability.
      const C: &AtomicU8 = &AtomicU8::new(0); // ERROR not allowed
      }

      #![allow(unused)]
      fn main() {
      use core::sync::atomic::AtomicU8;
      // As above.
      let _: &_ = const { &AtomicU8::new(0) }; // ERROR not allowed
      }

      #![allow(unused)]
      fn main() {
      #![allow(static_mut_refs)]
      // Even though this borrow is mutable, it's not of a temporary, so
      // this is allowed.
      const C: &u8 = unsafe { static mut S: u8 = 0; &mut S }; // OK
      }

      #![allow(unused)]
      fn main() {
      use core::sync::atomic::AtomicU8;
      // Even though this borrow is of a value with interior mutability,
      // it's not of a temporary, so this is allowed.
      const C: &AtomicU8 = {
          static S: AtomicU8 = AtomicU8::new(0); &S // OK
      };
      }

      #![allow(unused)]
      fn main() {
      use core::sync::atomic::AtomicU8;
      // This shared borrow of an interior mutable temporary is allowed
      // because its scope is not extended.
      const C: () = { _ = &AtomicU8::new(0); }; // OK
      }

      #![allow(unused)]
      fn main() {
      // Even though the borrow is mutable and the temporary lives to the
      // end of the program due to promotion, this is allowed because the
      // borrow is not in tail position and so the scope of the temporary
      // is not extended via temporary lifetime extension.
      const C: () = { let _: &'static mut [u8] = &mut []; }; // OK
      //                                              ~~
      //                                     Promoted temporary.
      }

  > Note

  > In other words — to focus on what’s allowed rather than what’s not allowed — shared borrows of interior mutable data and mutable borrows are only allowed in a const context when the borrowed place expression is transient, indirect, or static.

  > A place expression is transient if it is a variable local to the current const context or an expression whose temporary scope is contained inside the current const context.

  >     #![allow(unused)]
  >     fn main() {
  >     // The borrow is of a variable local to the initializer, therefore
  >     // this place expression is transient.
  >     const C: () = { let mut x = 0; _ = &mut x; };
  >     }

  >     #![allow(unused)]
  >     fn main() {
  >     // The borrow is of a temporary whose scope has not been extended,
  >     // therefore this place expression is transient.
  >     const C: () = { _ = &mut 0u8; };
  >     }

  >     #![allow(unused)]
  >     fn main() {
  >     // When a temporary is promoted but not lifetime extended, its
  >     // place expression is still treated as transient.
  >     const C: () = { let _: &'static mut [u8] = &mut []; };
  >     }

  > A place expression is indirect if it is a dereference expression.

  >     #![allow(unused)]
  >     fn main() {
  >     const C: () = { _ = &mut *(&mut 0); };
  >     }

  > A place expression is static if it is a `static` item.

  >     #![allow(unused)]
  >     fn main() {
  >     #![allow(static_mut_refs)]
  >     const C: &u8 = unsafe { static mut S: u8 = 0; &mut S };
  >     }

  > Note

  > One surprising consequence of these rules is that we allow this,

  >     #![allow(unused)]
  >     fn main() {
  >     const C: &[u8] = { let x: &mut [u8] = &mut []; x }; // OK
  >     //                                    ~~~~~~~
  >     // Empty arrays are promoted even behind mutable borrows.
  >     }

  > but we disallow this similar code:

  >     #![allow(unused)]
  >     fn main() {
  >     const C: &[u8] = &mut []; // ERROR
  >     //               ~~~~~~~
  >     //           Tail expression.
  >     }

  > The difference between these is that, in the first, the empty array is promoted but its scope does not undergo temporary lifetime extension, so we consider the place expression to be transient (even though after promotion the place indeed lives to the end of the program). In the second, the scope of the empty array temporary does undergo lifetime extension, and so it is rejected due to being a mutable borrow of a lifetime-extended temporary (and therefore borrowing a non-transient place expression).

  > The effect is surprising because temporary lifetime extension, in this case, causes less code to compile than would without it.

  > See issue #143129 for more details.

[const-eval.const-expr.deref]

- Dereference expressions.

      #![allow(unused)]
      fn main() {
      use core::cell::UnsafeCell;
      const _: u8 = unsafe {
          let x: *mut u8 = &raw mut *&mut 0;
          //                        ^^^^^^^
          //             Dereference of mutable reference.
          *x = 1; // Dereference of mutable pointer.
          *(x as *const u8) // Dereference of constant pointer.
      };
      const _: u8 = unsafe {
          let x = &UnsafeCell::new(0);
          *x.get() = 1; // Mutation of interior mutable value.
          *x.get()
      };
      }

[const-eval.const-expr.group]

- Grouped expressions.

[const-eval.const-expr.cast]

- Cast expressions, except
  - pointer to address casts and
  - function pointer to address casts.

[const-eval.const-expr.const-fn]

- Calls of const functions and const methods.

[const-eval.const-expr.loop]

- loop and while expressions.

[const-eval.const-expr.if-match]

- if and match expressions.

[const-eval.const-context]

## Const context

[const-eval.const-context.general]

A const context is one of the following:

[const-eval.const-context.array-length]

- Array type length expressions

[const-eval.const-context.repeat-length]

- Array repeat length expressions

[const-eval.const-context.init]

- The initializer of
  - constants
  - statics
  - enum discriminants

[const-eval.const-context.generic]

- A const generic argument

[const-eval.const-context.block]

- A const block

[const-eval.const-context.outer-generics]

Const contexts that are used as parts of types (array type and repeat length expressions as well as const generic arguments) can only make restricted use of surrounding generic parameters: such an expression must either be a single bare const generic parameter, or an arbitrary expression not making use of any generics.

[const-eval.const-fn]

## Const functions

[const-eval.const-fn.intro]

A const function is a function that can be called from a const context. It is defined with the `const` qualifier, and also includes tuple struct and tuple enum variant constructors.

> Example

>     #![allow(unused)]
>     fn main() {
>     const fn square(x: i32) -> i32 { x * x }

>     const VALUE: i32 = square(12);
>     }

[const-eval.const-fn.const-context]

When called from a const context, a const function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So `usize` is `32` bits if you are compiling against a `32` bit system, irrelevant of whether you are building on a `64` bit or a `32` bit system.

[const-eval.const-fn.outside-context]

When a const function is called from outside a const context, it behaves the same as if it did not have the `const` qualifier.

[const-eval.const-fn.body-restriction]

The body of a const function may only use constant expressions.

[const-eval.const-fn.async]

Const functions are not allowed to be async.

[const-eval.const-fn.type-restrictions]

The types of a const function’s parameters and return type are restricted to those that are compatible with a const context.

[abi]

# Application binary interface (ABI)

[abi.intro]

This section documents features that affect the ABI of the compiled output of a crate.

See extern functions for information on specifying the ABI for exporting functions. See external blocks for information on specifying the ABI for linking external libraries.

[abi.used]

## The `used` attribute

[abi.used.intro]

The `used` attribute can only be applied to `static` items. This attribute forces the compiler to keep the variable in the output object file (.o, .rlib, etc. excluding final binaries) even if the variable is not used, or referenced, by any other item in the crate. However, the linker is still free to remove such an item.

Below is an example that shows under what conditions the compiler keeps a `static` item in the output object file.

    #![allow(unused)]
    fn main() {
    // foo.rs

    // This is kept because of `#[used]`:
    #[used]
    static FOO: u32 = 0;

    // This is removable because it is unused:
    #[allow(dead_code)]
    static BAR: u32 = 0;

    // This is kept because it is publicly reachable:
    pub static BAZ: u32 = 0;

    // This is kept because it is referenced by a public, reachable function:
    static QUUX: u32 = 0;

    pub fn quux() -> &'static u32 {
        &QUUX
    }

    // This is removable because it is referenced by a private, unused (dead) function:
    static CORGE: u32 = 0;

    #[allow(dead_code)]
    fn corge() -> &'static u32 {
        &CORGE
    }
    }

    $ rustc -O --emit=obj --crate-type=rlib foo.rs

    $ nm -C foo.o
    0000000000000000 R foo::BAZ
    0000000000000000 r foo::FOO
    0000000000000000 R foo::QUUX
    0000000000000000 T foo::quux

[abi.no_mangle]

## The `no_mangle` attribute

[abi.no_mangle.intro]

The `no_mangle` attribute may be used on any item to disable standard symbol name mangling. The symbol for the item will be the identifier of the item’s name.

[abi.no_mangle.publicly-exported]

Additionally, the item will be publicly exported from the produced library or object file, similar to the `used` attribute.

[abi.no_mangle.unsafe]

This attribute is unsafe as an unmangled symbol may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.

    #![allow(unused)]
    fn main() {
    #[unsafe(no_mangle)]
    extern "C" fn foo() {}
    }

[abi.no_mangle.edition2024]

> 2024 Edition differences

> Before the 2024 edition it is allowed to use the `no_mangle` attribute without the `unsafe` qualification.

[abi.link_section]

## The `link_section` attribute

[abi.link_section.intro]

The `link_section` attribute specifies the section of the object file that a function or static’s content will be placed into.

[abi.link_section.syntax]

The `link_section` attribute uses the MetaNameValueStr syntax to specify the section name.

    #![allow(unused)]
    fn main() {
    #[unsafe(no_mangle)]
    #[unsafe(link_section = ".example_section")]
    pub static VAR1: u32 = 1;
    }

[abi.link_section.unsafe]

This attribute is unsafe as it allows users to place data and code into sections of memory not expecting them, such as mutable data into read-only areas.

[abi.link_section.edition2024]

> 2024 Edition differences

> Before the 2024 edition it is allowed to use the `link_section` attribute without the `unsafe` qualification.

[abi.export_name]

## The `export_name` attribute

[abi.export_name.intro]

The `export_name` attribute specifies the name of the symbol that will be exported on a function or static.

[abi.export_name.syntax]

The `export_name` attribute uses the MetaNameValueStr syntax to specify the symbol name.

    #![allow(unused)]
    fn main() {
    #[unsafe(export_name = "exported_symbol_name")]
    pub fn name_in_rust() { }
    }

[abi.export_name.unsafe]

This attribute is unsafe as a symbol with a custom name may collide with another symbol with the same name (or with a well-known symbol), leading to undefined behavior.

[abi.export_name.edition2024]

> 2024 Edition differences

> Before the 2024 edition it is allowed to use the `export_name` attribute without the `unsafe` qualification.

[runtime]

# The Rust runtime

This section documents features that define some aspects of the Rust runtime.

[runtime.global_allocator]

## The `global_allocator` attribute

[runtime.global_allocator.intro]

The `global_allocator` attribute selects a memory allocator.

> Example

>     #![allow(unused)]
>     fn main() {
>     use core::alloc::{GlobalAlloc, Layout};
>     use std::alloc::System;

>     struct MyAllocator;

>     unsafe impl GlobalAlloc for MyAllocator {
>         unsafe fn alloc(&self, layout: Layout) -> *mut u8 {
>             unsafe { System.alloc(layout) }
>         }
>         unsafe fn dealloc(&self, ptr: *mut u8, layout: Layout) {
>             unsafe { System.dealloc(ptr, layout) }
>         }
>     }

>     #[global_allocator]
>     static GLOBAL: MyAllocator = MyAllocator;
>     }

[runtime.global_allocator.syntax]

The `global_allocator` attribute uses the MetaWord syntax.

[runtime.global_allocator.allowed-positions]

The `global_allocator` attribute may only be applied to a static item whose type implements the `GlobalAlloc` trait.

[runtime.global_allocator.duplicates]

The `global_allocator` attribute may only be used once on an item.

[runtime.global_allocator.single]

The `global_allocator` attribute may only be used once in the crate graph.

[runtime.global_allocator.stdlib]

The `global_allocator` attribute is exported from the standard library prelude.

[runtime.windows_subsystem]

## The `windows_subsystem` attribute

[runtime.windows_subsystem.intro]

The `windows_subsystem` attribute sets the subsystem when linking on a Windows target.

> Example

>     #![allow(unused)]
>     #![windows_subsystem = "windows"]
>     fn main() {
>     }

[runtime.windows_subsystem.syntax]

The `windows_subsystem` attribute uses the MetaNameValueStr syntax. Accepted values are `"console"` and `"windows"`.

[runtime.windows_subsystem.allowed-positions]

The `windows_subsystem` attribute may only be applied to the crate root.

[runtime.windows_subsystem.duplicates]

Only the first use of `windows_subsystem` has effect.

> Note

> `rustc` lints against any use following the first. This may become an error in the future.

[runtime.windows_subsystem.ignored]

The `windows_subsystem` attribute is ignored on non-Windows targets and non-`bin` crate types.

[runtime.windows_subsystem.console]

The `"console"` subsystem is the default. If a console process is run from an existing console then it will be attached to that console; otherwise a new console window will be created.

[runtime.windows_subsystem.windows]

The `"windows"` subsystem will run detached from any existing console.

> Note

> The `"windows"` subsystem is commonly used by GUI applications that do not want to display a console window on startup.

# Appendices

# Grammar summary

The following is a summary of the grammar production rules. For details on the syntax of this grammar, see notation.grammar.syntax.

## Lexer summary

Lexer
CHAR → <a Unicode scalar value>

NUL → U+0000

LINE_COMMENT →
// ( ~[/ ! LF] | // ) ~LF*
| //

BLOCK_COMMENT →
/*
( ~[* !] | ** | BLOCK_COMMENT_OR_DOC )
( BLOCK_COMMENT_OR_DOC | ~*/ )*
*/
| /**/
| /***/

INNER_LINE_DOC →
//! ~[LF CR]*

INNER_BLOCK_DOC →
/*! ( BLOCK_COMMENT_OR_DOC | ~[*/ CR] )* */

OUTER_LINE_DOC →
/// ( ~/ ~[LF CR]* )?

OUTER_BLOCK_DOC →
/**
( ~* | BLOCK_COMMENT_OR_DOC )
( BLOCK_COMMENT_OR_DOC | ~[*/ CR] )*
*/

BLOCK_COMMENT_OR_DOC →
BLOCK_COMMENT
| OUTER_BLOCK_DOC
| INNER_BLOCK_DOC

WHITESPACE →
U+0009 // Horizontal tab, `'\t'`
| U+000A // Line feed, `'\n'`
| U+000B // Vertical tab
| U+000C // Form feed
| U+000D // Carriage return, `'\r'`
| U+0020 // Space, `' '`
| U+0085 // Next line
| U+200E // Left-to-right mark
| U+200F // Right-to-left mark
| U+2028 // Line separator
| U+2029 // Paragraph separator

TAB → U+0009 // Horizontal tab, `'\t'`

LF → U+000A // Line feed, `'\n'`

CR → U+000D // Carriage return, `'\r'`

Token →
RESERVED_TOKEN
| RAW_IDENTIFIER
| CHAR_LITERAL
| STRING_LITERAL
| RAW_STRING_LITERAL
| BYTE_LITERAL
| BYTE_STRING_LITERAL
| RAW_BYTE_STRING_LITERAL
| C_STRING_LITERAL
| RAW_C_STRING_LITERAL
| FLOAT_LITERAL
| INTEGER_LITERAL
| LIFETIME_TOKEN
| PUNCTUATION
| IDENTIFIER_OR_KEYWORD

SUFFIX → IDENTIFIER_OR_KEYWORDexcept `_`

SUFFIX_NO_E → SUFFIXnot beginning with `e` or `E`

CHAR_LITERAL →
'
( ~[' \ LF CR TAB] | QUOTE_ESCAPE | ASCII_ESCAPE | UNICODE_ESCAPE )
' SUFFIX?

QUOTE_ESCAPE → \' | \"

ASCII_ESCAPE →
\x OCT_DIGIT HEX_DIGIT
| \n | \r | \t | \\ | \0

UNICODE_ESCAPE →
\u{ ( HEX_DIGIT _* )1..6valid hex char value }

STRING_LITERAL →
" (
~[" \ CR]
| QUOTE_ESCAPE
| ASCII_ESCAPE
| UNICODE_ESCAPE
| STRING_CONTINUE
)* " SUFFIX?

STRING_CONTINUE → \ LF

RAW_STRING_LITERAL → r RAW_STRING_CONTENT SUFFIX?

RAW_STRING_CONTENT →
" ( ~CR )* (non-greedy) "
| # RAW_STRING_CONTENT #

BYTE_LITERAL →
b' ( ASCII_FOR_CHAR | BYTE_ESCAPE ) ' SUFFIX?

ASCII_FOR_CHAR →
<any ASCII (i.e. 0x00 to 0x7F) except `'`, `\`, LF, CR, or TAB>

BYTE_ESCAPE →
\x HEX_DIGIT HEX_DIGIT
| \n | \r | \t | \\ | \0 | \' | \"

BYTE_STRING_LITERAL →
b" ( ASCII_FOR_STRING | BYTE_ESCAPE | STRING_CONTINUE )* " SUFFIX?

ASCII_FOR_STRING →
<any ASCII (i.e 0x00 to 0x7F) except `"`, `\`, or CR>

RAW_BYTE_STRING_LITERAL →
br RAW_BYTE_STRING_CONTENT SUFFIX?

RAW_BYTE_STRING_CONTENT →
" ASCII_FOR_RAW* (non-greedy) "
| # RAW_BYTE_STRING_CONTENT #

ASCII_FOR_RAW →
<any ASCII (i.e. 0x00 to 0x7F) except CR>

C_STRING_LITERAL →
c" (
~[" \ CR NUL]
| BYTE_ESCAPEexcept `\0` or `\x00`
| UNICODE_ESCAPEexcept `\u{0}`, `\u{00}`, …, `\u{000000}`
| STRING_CONTINUE
)* " SUFFIX?

RAW_C_STRING_LITERAL →
cr RAW_C_STRING_CONTENT SUFFIX?

RAW_C_STRING_CONTENT →
" ( ~[CR NUL] )* (non-greedy) "
| # RAW_C_STRING_CONTENT #

INTEGER_LITERAL →
( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL | DEC_LITERAL ) SUFFIX_NO_E?

DEC_LITERAL → DEC_DIGIT ( DEC_DIGIT | _ )*

BIN_LITERAL → 0b _* BIN_DIGIT ( BIN_DIGIT | _ )*

OCT_LITERAL → 0o _* OCT_DIGIT ( OCT_DIGIT | _ )*

HEX_LITERAL → 0x _* HEX_DIGIT ( HEX_DIGIT | _ )*

BIN_DIGIT → [0-1]

OCT_DIGIT → [0-7]

DEC_DIGIT → [0-9]

HEX_DIGIT → [0-9 a-f A-F]

TUPLE_INDEX → DEC_LITERAL | BIN_LITERAL | OCT_LITERAL | HEX_LITERAL

FLOAT_LITERAL →
DEC_LITERAL ( . DEC_LITERAL )? FLOAT_EXPONENT SUFFIX?
| DEC_LITERAL . DEC_LITERAL SUFFIX_NO_E?
| DEC_LITERAL .not immediately followed by `.`, `_` or an XID_Start character

FLOAT_EXPONENT →
( e | E ) ( + | - )? _* DEC_DIGIT ( DEC_DIGIT | _ )*

RESERVED_NUMBER →
BIN_LITERAL [2-9]
| OCT_LITERAL [8-9]
| ( BIN_LITERAL | OCT_LITERAL | HEX_LITERAL ) .not immediately followed by `.`, `_` or an XID_Start character
| ( BIN_LITERAL | OCT_LITERAL ) ( e | E )
| 0b _* <end of input or not BIN_DIGIT>
| 0o _* <end of input or not OCT_DIGIT>
| 0x _* <end of input or not HEX_DIGIT>
| DEC_LITERAL ( . DEC_LITERAL )? ( e | E ) ( + | - )? <end of input or not DEC_DIGIT>

LIFETIME_TOKEN →
RAW_LIFETIME
| ' IDENTIFIER_OR_KEYWORDnot immediately followed by `'`

LIFETIME_OR_LABEL →
RAW_LIFETIME
| ' NON_KEYWORD_IDENTIFIERnot immediately followed by `'`

RAW_LIFETIME →
'r# IDENTIFIER_OR_KEYWORDnot immediately followed by `'`

RESERVED_RAW_LIFETIME → 'r# ( _ | crate | self | Self | super )not immediately followed by `'`

PUNCTUATION →
...
| ..=
| <<=
| >>=
| !=
| %=
| &&
| &=
| *=
| +=
| -=
| ->
| ..
| /=
| ::
| <-
| <<
| <=
| ==
| =>
| >=
| >>
| >
| ^=
| |=
| ||
| !
| #
| $
| %
| &
| (
| )
| *
| +
| ,
| -
| .
| /
| :
| ;
| <
| =
| ?
| @
| [
| ]
| ^
| {
| |
| }
| ~

RESERVED_TOKEN →
RESERVED_GUARDED_STRING_LITERAL
| RESERVED_NUMBER
| RESERVED_POUNDS
| RESERVED_RAW_IDENTIFIER
| RESERVED_RAW_LIFETIME
| RESERVED_TOKEN_DOUBLE_QUOTE
| RESERVED_TOKEN_LIFETIME
| RESERVED_TOKEN_POUND
| RESERVED_TOKEN_SINGLE_QUOTE

RESERVED_TOKEN_DOUBLE_QUOTE →
IDENTIFIER_OR_KEYWORDexcept `b` or `c` or `r` or `br` or `cr` "

RESERVED_TOKEN_SINGLE_QUOTE →
IDENTIFIER_OR_KEYWORDexcept `b` '

RESERVED_TOKEN_POUND →
IDENTIFIER_OR_KEYWORDexcept `r` or `br` or `cr` #

RESERVED_TOKEN_LIFETIME →
' IDENTIFIER_OR_KEYWORDexcept `r` #

RESERVED_GUARDED_STRING_LITERAL → #+ STRING_LITERAL

RESERVED_POUNDS → #2..

IDENTIFIER_OR_KEYWORD → ( XID_Start | _ ) XID_Continue*

XID_Start → <`XID_Start` defined by Unicode>

XID_Continue → <`XID_Continue` defined by Unicode>

RAW_IDENTIFIER → r# IDENTIFIER_OR_KEYWORD

NON_KEYWORD_IDENTIFIER → IDENTIFIER_OR_KEYWORDexcept a strict or reserved keyword

IDENTIFIER → NON_KEYWORD_IDENTIFIER | RAW_IDENTIFIER

RESERVED_RAW_IDENTIFIER →
r# ( _ | crate | self | Self | super )not immediately followed by XID_Continue

## Macros summary

Syntax
MacroInvocation →
SimplePath ! DelimTokenTree

DelimTokenTree →
( TokenTree* )
| [ TokenTree* ]
| { TokenTree* }

TokenTree →
Tokenexcept delimiters | DelimTokenTree

MacroInvocationSemi →
SimplePath ! ( TokenTree* ) ;
| SimplePath ! [ TokenTree* ] ;
| SimplePath ! { TokenTree* }

MacroRulesDefinition →
macro_rules ! IDENTIFIER MacroRulesDef

MacroRulesDef →
( MacroRules ) ;
| [ MacroRules ] ;
| { MacroRules }

MacroRules →
MacroRule ( ; MacroRule )* ;?

MacroRule →
MacroMatcher => MacroTranscriber

MacroMatcher →
( MacroMatch* )
| [ MacroMatch* ]
| { MacroMatch* }

MacroMatch →
Tokenexcept `$` and delimiters
| MacroMatcher
| $ ( IDENTIFIER_OR_KEYWORDexcept `crate` | RAW_IDENTIFIER ) : MacroFragSpec
| $ ( MacroMatch+ ) MacroRepSep? MacroRepOp

MacroFragSpec →
block | expr | expr_2021 | ident | item | lifetime | literal
| meta | pat | pat_param | path | stmt | tt | ty | vis

MacroRepSep → Tokenexcept delimiters and MacroRepOp

MacroRepOp → * | + | ?

MacroTranscriber → DelimTokenTree

## Patterns summary

Syntax
Pattern → |? PatternNoTopAlt ( | PatternNoTopAlt )*

PatternNoTopAlt →
PatternWithoutRange
| RangePattern

PatternWithoutRange →
LiteralPattern
| IdentifierPattern
| WildcardPattern
| RestPattern
| ReferencePattern
| StructPattern
| TupleStructPattern
| TuplePattern
| GroupedPattern
| SlicePattern
| PathPattern
| MacroInvocation

LiteralPattern → -? LiteralExpression

IdentifierPattern → ref? mut? IDENTIFIER ( @ PatternNoTopAlt )?

WildcardPattern → _

RestPattern → ..

RangePattern →
RangeExclusivePattern
| RangeInclusivePattern
| RangeFromPattern
| RangeToExclusivePattern
| RangeToInclusivePattern
| ObsoleteRangePattern

RangeExclusivePattern →
RangePatternBound .. RangePatternBound

RangeInclusivePattern →
RangePatternBound ..= RangePatternBound

RangeFromPattern →
RangePatternBound ..

RangeToExclusivePattern →
.. RangePatternBound

RangeToInclusivePattern →
..= RangePatternBound

ObsoleteRangePattern →
RangePatternBound ... RangePatternBound

RangePatternBound →
LiteralPattern
| PathExpression

ReferencePattern → ( & | && ) mut? PatternWithoutRange

StructPattern →
PathInExpression {
StructPatternElements?
}

StructPatternElements →
StructPatternFields ( , | , StructPatternEtCetera )?
| StructPatternEtCetera

StructPatternFields →
StructPatternField ( , StructPatternField )*

StructPatternField →
OuterAttribute*
(
TUPLE_INDEX : Pattern
| IDENTIFIER : Pattern
| ref? mut? IDENTIFIER
)

StructPatternEtCetera → ..

TupleStructPattern → PathInExpression ( TupleStructItems? )

TupleStructItems → Pattern ( , Pattern )* ,?

TuplePattern → ( TuplePatternItems? )

TuplePatternItems →
Pattern ,
| RestPattern
| Pattern ( , Pattern )+ ,?

GroupedPattern → ( Pattern )

SlicePattern → [ SlicePatternItems? ]

SlicePatternItems → Pattern ( , Pattern )* ,?

PathPattern → PathExpression

## Items summary

Syntax
Crate →
InnerAttribute*
Item*

Item →
OuterAttribute* ( VisItem | MacroItem )

VisItem →
Visibility?
(
Module
| ExternCrate
| UseDeclaration
| Function
| TypeAlias
| Struct
| Enumeration
| Union
| ConstantItem
| StaticItem
| Trait
| Implementation
| ExternBlock
)

MacroItem →
MacroInvocationSemi
| MacroRulesDefinition

StaticItem →
ItemSafety? static mut? IDENTIFIER : Type ( = Expression )? ;

Struct →
StructStruct
| TupleStruct

StructStruct →
struct IDENTIFIER GenericParams? WhereClause? ( { StructFields? } | ; )

TupleStruct →
struct IDENTIFIER GenericParams? ( TupleFields? ) WhereClause? ;

StructFields → StructField ( , StructField )* ,?

StructField → OuterAttribute* Visibility? IDENTIFIER : Type

TupleFields → TupleField ( , TupleField )* ,?

TupleField → OuterAttribute* Visibility? Type

Module →
unsafe? mod IDENTIFIER ;
| unsafe? mod IDENTIFIER {
InnerAttribute*
Item*
}

Implementation → InherentImpl | TraitImpl

InherentImpl →
impl GenericParams? Type WhereClause? {
InnerAttribute*
AssociatedItem*
}

TraitImpl →
unsafe? impl GenericParams? !? TypePath for Type
WhereClause?
{
InnerAttribute*
AssociatedItem*
}

AssociatedItem →
OuterAttribute* (
MacroInvocationSemi
| ( Visibility? ( TypeAlias | ConstantItem | Function ) )
)

Function →
FunctionQualifiers fn IDENTIFIER GenericParams?
( FunctionParameters? )
FunctionReturnType? WhereClause?
( BlockExpression | ; )

FunctionQualifiers → const? async? ItemSafety? ( extern Abi? )?

ItemSafety → safe | unsafe

Abi → STRING_LITERAL | RAW_STRING_LITERAL

FunctionParameters →
SelfParam ,?
| ( SelfParam , )? FunctionParam ( , FunctionParam )* ,?

SelfParam → OuterAttribute* ( ShorthandSelf | TypedSelf )

ShorthandSelf → ( & | & Lifetime )? mut? self

TypedSelf → mut? self : Type

FunctionParam → OuterAttribute* ( FunctionParamPattern | ... | Type )

FunctionParamPattern → PatternNoTopAlt : ( Type | ... )

FunctionReturnType → -> Type

Trait →
unsafe? trait IDENTIFIER GenericParams? ( : TypeParamBounds? )? WhereClause?
{
InnerAttribute*
AssociatedItem*
}

Union →
union IDENTIFIER GenericParams? WhereClause? { StructFields? }

ExternCrate → extern crate CrateRef AsClause? ;

CrateRef → IDENTIFIER | self

AsClause → as ( IDENTIFIER | _ )

ConstantItem →
const ( IDENTIFIER | _ ) : Type ( = Expression )? ;

GenericParams → < ( GenericParam ( , GenericParam )* ,? )? >

GenericParam → OuterAttribute* ( LifetimeParam | TypeParam | ConstParam )

LifetimeParam → Lifetime ( : LifetimeBounds )?

TypeParam → IDENTIFIER ( : TypeParamBounds? )? ( = Type )?

ConstParam →
const IDENTIFIER : Type
( = ( BlockExpression | IDENTIFIER | -? LiteralExpression ) )?

WhereClause → where ( WhereClauseItem , )* WhereClauseItem?

WhereClauseItem →
LifetimeWhereClauseItem
| TypeBoundWhereClauseItem

LifetimeWhereClauseItem → Lifetime : LifetimeBounds

TypeBoundWhereClauseItem → ForLifetimes? Type : TypeParamBounds?

TypeAlias →
type IDENTIFIER GenericParams? ( : TypeParamBounds )?
WhereClause?
( = Type WhereClause? )? ;

UseDeclaration → use UseTree ;

UseTree →
( SimplePath? :: )? *
| ( SimplePath? :: )? { ( UseTree ( , UseTree )* ,? )? }
| SimplePath ( as ( IDENTIFIER | _ ) )?

ExternBlock →
unsafe? extern Abi? {
InnerAttribute*
ExternalItem*
}

ExternalItem →
OuterAttribute* (
MacroInvocationSemi
| Visibility? StaticItem
| Visibility? Function
)

Enumeration →
enum IDENTIFIER GenericParams? WhereClause? { EnumVariants? }

EnumVariants → EnumVariant ( , EnumVariant )* ,?

EnumVariant →
OuterAttribute* Visibility?
IDENTIFIER ( EnumVariantTuple | EnumVariantStruct )? EnumVariantDiscriminant?

EnumVariantTuple → ( TupleFields? )

EnumVariantStruct → { StructFields? }

EnumVariantDiscriminant → = Expression

Visibility →
pub
| pub ( crate )
| pub ( self )
| pub ( super )
| pub ( in SimplePath )

## Miscellaneous summary

Syntax
TypeParamBounds → TypeParamBound ( + TypeParamBound )* +?

TypeParamBound → Lifetime | TraitBound | UseBound

TraitBound →
( ? | ForLifetimes )? TypePath
| ( ( ? | ForLifetimes )? TypePath )

LifetimeBounds → ( Lifetime + )* Lifetime?

Lifetime →
LIFETIME_OR_LABEL
| 'static
| '_

UseBound → use UseBoundGenericArgs

UseBoundGenericArgs →
< >
| < ( UseBoundGenericArg , )* UseBoundGenericArg ,? >

UseBoundGenericArg →
Lifetime
| IDENTIFIER
| Self

ForLifetimes → for GenericParams

## Paths summary

Syntax
SimplePath →
::? SimplePathSegment ( :: SimplePathSegment )*

SimplePathSegment →
IDENTIFIER | super | self | crate | $crate

PathInExpression →
::? PathExprSegment ( :: PathExprSegment )*

PathExprSegment →
PathIdentSegment ( :: GenericArgs )?

PathIdentSegment →
IDENTIFIER | super | self | Self | crate | $crate

GenericArgs →
< >
| < ( GenericArg , )* GenericArg ,? >

GenericArg →
Lifetime | Type | GenericArgsConst | GenericArgsBinding | GenericArgsBounds

GenericArgsConst →
BlockExpression
| LiteralExpression
| - LiteralExpression
| SimplePathSegment

GenericArgsBinding →
IDENTIFIER GenericArgs? = Type

GenericArgsBounds →
IDENTIFIER GenericArgs? : TypeParamBounds

QualifiedPathInExpression → QualifiedPathType ( :: PathExprSegment )+

QualifiedPathType → < Type ( as TypePath )? >

QualifiedPathInType → QualifiedPathType ( :: TypePathSegment )+

TypePath → ::? TypePathSegment ( :: TypePathSegment )*

TypePathSegment → PathIdentSegment ( ::? ( GenericArgs | TypePathFn ) )?

TypePathFn → ( TypePathFnInputs? ) ( -> TypeNoBounds )?

TypePathFnInputs → Type ( , Type )* ,?

## Statements summary

Syntax
Statement →
;
| Item
| LetStatement
| ExpressionStatement
| OuterAttribute* MacroInvocationSemi

LetStatement →
OuterAttribute* let PatternNoTopAlt ( : Type )?
(
= Expression
| = Expressionexcept LazyBooleanExpression or end with a `}` else BlockExpression
)? ;

ExpressionStatement →
ExpressionWithoutBlock ;
| ExpressionWithBlock ;?

## Attributes summary

Syntax
ProcMacroDeriveAttribute →
proc_macro_derive ( DeriveMacroName ( , DeriveMacroAttributes )? ,? )

DeriveMacroName → IDENTIFIER

DeriveMacroAttributes →
attributes ( ( IDENTIFIER ( , IDENTIFIER )* ,? )? )

CollapseDebuginfoAttribute → collapse_debuginfo ( CollapseDebuginfoOption )

CollapseDebuginfoOption →
yes
| no
| external

InlineAttribute →
inline ( always )
| inline ( never )
| inline

InnerAttribute → # ! [ Attr ]

OuterAttribute → # [ Attr ]

Attr →
SimplePath AttrInput?
| unsafe ( SimplePath AttrInput? )

AttrInput →
DelimTokenTree
| = Expression

MetaItem →
SimplePath
| SimplePath = Expression
| SimplePath ( MetaSeq? )

MetaSeq →
MetaItemInner ( , MetaItemInner )* ,?

MetaItemInner →
MetaItem
| Expression

MetaWord →
IDENTIFIER

MetaNameValueStr →
IDENTIFIER = ( STRING_LITERAL | RAW_STRING_LITERAL )

MetaListPaths →
IDENTIFIER ( ( SimplePath ( , SimplePath )* ,? )? )

MetaListIdents →
IDENTIFIER ( ( IDENTIFIER ( , IDENTIFIER )* ,? )? )

MetaListNameValueStr →
IDENTIFIER ( ( MetaNameValueStr ( , MetaNameValueStr )* ,? )? )

## Configuration summary

Syntax
ConfigurationPredicate →
ConfigurationOption
| ConfigurationAll
| ConfigurationAny
| ConfigurationNot
| true
| false

ConfigurationOption →
IDENTIFIER ( = ( STRING_LITERAL | RAW_STRING_LITERAL ) )?

ConfigurationAll →
all ( ConfigurationPredicateList? )

ConfigurationAny →
any ( ConfigurationPredicateList? )

ConfigurationNot →
not ( ConfigurationPredicate )

ConfigurationPredicateList →
ConfigurationPredicate ( , ConfigurationPredicate )* ,?

CfgAttribute → cfg ( ConfigurationPredicate )

CfgAttrAttribute → cfg_attr ( ConfigurationPredicate , CfgAttrs? )

CfgAttrs → Attr ( , Attr )* ,?

## Assembly summary

Syntax
AsmArgs → AsmAttrFormatString ( , AsmAttrFormatString )* ( , AsmAttrOperand )* ,?

FormatString → STRING_LITERAL | RAW_STRING_LITERAL | MacroInvocation

AsmAttrFormatString → ( OuterAttribute )* FormatString

AsmOperand →
ClobberAbi
| AsmOptions
| RegOperand

AsmAttrOperand → ( OuterAttribute )* AsmOperand

ClobberAbi → clobber_abi ( Abi ( , Abi )* ,? )

AsmOptions →
options ( ( AsmOption ( , AsmOption )* ,? )? )

AsmOption →
pure
| nomem
| readonly
| preserves_flags
| noreturn
| nostack
| att_syntax
| raw

RegOperand → ( ParamName = )?
(
DirSpec ( RegSpec ) Expression
| DualDirSpec ( RegSpec ) DualDirSpecExpression
| sym PathExpression
| const Expression
| label { Statements? }
)

ParamName → IDENTIFIER_OR_KEYWORD | RAW_IDENTIFIER

DualDirSpecExpression →
Expression
| Expression => Expression

RegSpec → RegisterClass | ExplicitRegister

RegisterClass → IDENTIFIER_OR_KEYWORD

ExplicitRegister → STRING_LITERAL

DirSpec →
in
| out
| lateout

DualDirSpec →
inout
| inlateout

## Types summary

Syntax
TupleType →
( )
| ( ( Type , )+ Type? )

BareFunctionType →
ForLifetimes? FunctionTypeQualifiers fn
( FunctionParametersMaybeNamedVariadic? ) BareFunctionReturnType?

FunctionTypeQualifiers → unsafe? ( extern Abi? )?

BareFunctionReturnType → -> TypeNoBounds

FunctionParametersMaybeNamedVariadic →
MaybeNamedFunctionParameters | MaybeNamedFunctionParametersVariadic

MaybeNamedFunctionParameters →
MaybeNamedParam ( , MaybeNamedParam )* ,?

MaybeNamedParam →
OuterAttribute* ( ( IDENTIFIER | _ ) : )? Type

MaybeNamedFunctionParametersVariadic →
( MaybeNamedParam , )* MaybeNamedParam , OuterAttribute* ...

ArrayType → [ Type ; Expression ]

NeverType → !

InferredType → _

TraitObjectType → dyn? TypeParamBounds

TraitObjectTypeOneBound → dyn? TraitBound

SliceType → [ Type ]

ReferenceType → & Lifetime? mut? TypeNoBounds

RawPointerType → * ( mut | const ) TypeNoBounds

ImplTraitType → impl TypeParamBounds

ImplTraitTypeOneBound → impl TraitBound

Type →
TypeNoBounds
| ImplTraitType
| TraitObjectType

TypeNoBounds →
ParenthesizedType
| ImplTraitTypeOneBound
| TraitObjectTypeOneBound
| TypePath
| TupleType
| NeverType
| RawPointerType
| ReferenceType
| ArrayType
| SliceType
| InferredType
| QualifiedPathInType
| BareFunctionType
| MacroInvocation

ParenthesizedType → ( Type )

## Expressions summary

Syntax
ReturnExpression → return Expression?

FieldExpression → Expression . IDENTIFIER

StructExpression →
PathInExpression { ( StructExprFields | StructBase )? }

StructExprFields →
StructExprField ( , StructExprField )* ( , StructBase | ,? )

StructExprField →
OuterAttribute*
(
IDENTIFIER
| ( IDENTIFIER | TUPLE_INDEX ) : Expression
)

StructBase → .. Expression

ArrayExpression → [ ArrayElements? ]

ArrayElements →
Expression ( , Expression )* ,?
| Expression ; Expression

IndexExpression → Expression [ Expression ]

LiteralExpression →
CHAR_LITERAL
| STRING_LITERAL
| RAW_STRING_LITERAL
| BYTE_LITERAL
| BYTE_STRING_LITERAL
| RAW_BYTE_STRING_LITERAL
| C_STRING_LITERAL
| RAW_C_STRING_LITERAL
| INTEGER_LITERAL
| FLOAT_LITERAL
| true
| false

ClosureExpression →
async?
move?
( || | | ClosureParameters? | )
( Expression | -> TypeNoBounds BlockExpression )

ClosureParameters → ClosureParam ( , ClosureParam )* ,?

ClosureParam → OuterAttribute* PatternNoTopAlt ( : Type )?

MatchExpression →
match Scrutinee {
InnerAttribute*
MatchArms?
}

Scrutinee → Expressionexcept StructExpression

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

MatchArm → OuterAttribute* Pattern MatchArmGuard?

MatchArmGuard → if Expression

AwaitExpression → Expression . await

UnderscoreExpression → _

MethodCallExpression → Expression . PathExprSegment ( CallParams? )

IfExpression →
if Conditions BlockExpression
( else ( BlockExpression | IfExpression ) )?

Conditions →
Expressionexcept StructExpression
| LetChain

LetChain → LetChainCondition ( && LetChainCondition )*

LetChainCondition →
Expressionexcept ExcludedConditions
| OuterAttribute* let Pattern = Scrutineeexcept ExcludedConditions

ExcludedConditions →
StructExpression
| LazyBooleanExpression
| RangeExpr
| RangeFromExpr
| RangeInclusiveExpr
| AssignmentExpression
| CompoundAssignmentExpression

PathExpression →
PathInExpression
| QualifiedPathInExpression

OperatorExpression →
BorrowExpression
| DereferenceExpression
| TryPropagationExpression
| NegationExpression
| ArithmeticOrLogicalExpression
| ComparisonExpression
| LazyBooleanExpression
| TypeCastExpression
| AssignmentExpression
| CompoundAssignmentExpression

BorrowExpression →
( & | && ) Expression
| ( & | && ) mut Expression
| ( & | && ) raw const Expression
| ( & | && ) raw mut Expression

DereferenceExpression → * Expression

TryPropagationExpression → Expression ?

NegationExpression →
- Expression
| ! Expression

ArithmeticOrLogicalExpression →
Expression + Expression
| Expression - Expression
| Expression * Expression
| Expression / Expression
| Expression % Expression
| Expression & Expression
| Expression | Expression
| Expression ^ Expression
| Expression << Expression
| Expression >> Expression

ComparisonExpression →
Expression == Expression
| Expression != Expression
| Expression > Expression
| Expression < Expression
| Expression >= Expression
| Expression <= Expression

LazyBooleanExpression →
Expression || Expression
| Expression && Expression

TypeCastExpression → Expression as TypeNoBounds

AssignmentExpression → Expression = Expression

CompoundAssignmentExpression →
Expression += Expression
| Expression -= Expression
| Expression *= Expression
| Expression /= Expression
| Expression %= Expression
| Expression &= Expression
| Expression |= Expression
| Expression ^= Expression
| Expression <<= Expression
| Expression >>= Expression

BlockExpression →
{
InnerAttribute*
Statements?
}

Statements →
Statement+
| Statement+ ExpressionWithoutBlock
| ExpressionWithoutBlock

AsyncBlockExpression → async move? BlockExpression

ConstBlockExpression → const BlockExpression

UnsafeBlockExpression → unsafe BlockExpression

RangeExpression →
RangeExpr
| RangeFromExpr
| RangeToExpr
| RangeFullExpr
| RangeInclusiveExpr
| RangeToInclusiveExpr

RangeExpr → Expression .. Expression

RangeFromExpr → Expression ..

RangeToExpr → .. Expression

RangeFullExpr → ..

RangeInclusiveExpr → Expression ..= Expression

RangeToInclusiveExpr → ..= Expression

TupleExpression → ( TupleElements? )

TupleElements → ( Expression , )+ Expression?

TupleIndexingExpression → Expression . TUPLE_INDEX

GroupedExpression → ( Expression )

CallExpression → Expression ( CallParams? )

CallParams → Expression ( , Expression )* ,?

LoopExpression →
LoopLabel? (
InfiniteLoopExpression
| PredicateLoopExpression
| IteratorLoopExpression
| LabelBlockExpression
)

InfiniteLoopExpression → loop BlockExpression

PredicateLoopExpression → while Conditions BlockExpression

IteratorLoopExpression →
for Pattern in Expressionexcept StructExpression BlockExpression

LoopLabel → LIFETIME_OR_LABEL :

BreakExpression → break LIFETIME_OR_LABEL? Expression?

LabelBlockExpression → BlockExpression

ContinueExpression → continue LIFETIME_OR_LABEL?

Expression →
ExpressionWithoutBlock
| ExpressionWithBlock

ExpressionWithoutBlock →
OuterAttribute*
(
LiteralExpression
| PathExpression
| OperatorExpression
| GroupedExpression
| ArrayExpression
| AwaitExpression
| IndexExpression
| TupleExpression
| TupleIndexingExpression
| StructExpression
| CallExpression
| MethodCallExpression
| FieldExpression
| ClosureExpression
| AsyncBlockExpression
| ContinueExpression
| BreakExpression
| RangeExpression
| ReturnExpression
| UnderscoreExpression
| MacroInvocation
)

ExpressionWithBlock →
OuterAttribute*
(
BlockExpression
| ConstBlockExpression
| UnsafeBlockExpression
| LoopExpression
| IfExpression
| MatchExpression
)

# Syntax index

This appendix provides an index of tokens and common forms with links to where those elements are defined.

## Keywords

Keyword | Use
--- | ---
`_` | wildcard pattern, inferred const, inferred type, placeholder lifetime, constant items, extern crate, use declarations, destructuring assignment
`abstract` | reserved keyword
`as` | extern crate, use declarations, type cast expressions, qualified paths
`async` | async functions, async blocks, async closures
`await` | await expressions
`become` | reserved keyword
`box` | reserved keyword
`break` | break expressions
`const` | const functions, const items, const generics, const blocks, raw borrow operator, raw pointer type, const assembly operands
`continue` | continue expressions
`crate` | extern crate, visibility, paths
`do` | reserved keyword
`dyn` | trait objects
`else` | let statements, if expressions
`enum` | enumerations
`extern` | extern crate, extern function qualifier, external blocks, extern function pointer types
`false` | boolean type, boolean expressions, configuration predicates
`final` | reserved keyword
`fn` | functions, function pointer types
`for` | trait implementations, iterator loops, higher-ranked trait bounds
`gen` | reserved keyword
`if` | if expressions, match guards
`impl` | inherent impls, trait impls, impl trait types, anonymous type parameters
`in` | visibility, iterator loops, assembly operands
`let` | let statements, `if let` patterns
`loop` | infinite loops
`macro_rules` | macros by example
`macro` | reserved keyword
`match` | match expressions
`mod` | modules
`move` | closure expressions, async blocks
`mut` | borrow expressions, identifier patterns, reference patterns, struct patterns, reference types, raw pointer types, self parameters, static items
`override` | reserved keyword
`priv` | reserved keyword
`pub` | visibility
`raw` | borrow expressions, raw assembly
`ref` | identifier patterns, struct patterns
`return` | return expressions
`safe` | external block functions, external block statics
`self` | extern crate, self parameters, visibility, `self` paths
`Self` | `Self` type paths, use bounds
`static` | static items, `'static` lifetimes
`struct` | structs
`super` | super paths, visibility
`trait` | trait items
`true` | boolean type, boolean expressions, configuration predicates
`try` | reserved keyword
`type` | type aliases
`typeof` | reserved keyword
`union` | union items
`unsafe` | unsafe blocks, unsafe attributes, unsafe modules, unsafe functions, unsafe external blocks, unsafe external functions, unsafe external statics, unsafe traits, unsafe trait implementations
`unsized` | reserved keyword
`use` | use items, use bounds
`virtual` | reserved keyword
`where` | where clauses
`while` | predicate loops
`yield` | reserved keyword

## Operators and punctuation

Symbol | Name | Use
--- | --- | ---
`+` | Plus | addition, trait bounds, macro Kleene matcher
`-` | Minus | subtraction, negation
`*` | Star | multiplication, dereference, raw pointers, macro Kleene matcher, glob imports
`/` | Slash | division
`%` | Percent | remainder
`^` | Caret | bitwise and logical XOR
`!` | Not | bitwise and logical NOT, macro calls, inner attributes, never type, negative impls
`&` | And | bitwise and logical AND, borrow, references, reference patterns
`|` | Or | bitwise and logical OR, closures, or patterns, if let, while let
`&&` | AndAnd | lazy AND, borrow, references, reference patterns
`||` | OrOr | lazy OR, closures
`<<` | Shl | shift left, nested generics
`>>` | Shr | shift right, nested generics
`+=` | PlusEq | addition assignment
`-=` | MinusEq | subtraction assignment
`*=` | StarEq | multiplication assignment
`/=` | SlashEq | division assignment
`%=` | PercentEq | remainder assignment
`^=` | CaretEq | bitwise XOR assignment
`&=` | AndEq | bitwise AND assignment
`|=` | OrEq | bitwise OR assignment
`<<=` | ShlEq | shift left assignment
`>>=` | ShrEq | shift right assignment, nested generics
`=` | Eq | assignment, let statements, attributes, various type definitions
`==` | EqEq | equal
`!=` | Ne | not equal
`>` | Gt | greater than, generics, paths, use bounds
`<` | Lt | less than, generics, paths, use bounds
`>=` | Ge | greater than or equal to, generics
`<=` | Le | less than or equal to
`@` | At | subpattern binding
`.` | Dot | field access, tuple index
`..` | DotDot | range expressions, struct expressions, rest pattern, range patterns, struct patterns
`...` | DotDotDot | variadic functions, range patterns
`..=` | DotDotEq | inclusive range expressions, range patterns
`,` | Comma | various separators
`;` | Semi | terminator for various items and statements, array expressions, array types
`:` | Colon | various separators
`::` | PathSep | path separator
`->` | RArrow | functions, closures, function pointer type
`=>` | FatArrow | match arms, macros
`<-` | LArrow | The left arrow symbol has been unused since before Rust 1.0, but it is still treated as a single token.
`#` | Pound | attributes, raw string literals, raw byte string literals, raw C string literals
`$` | Dollar | macros
`?` | Question | try propagation expressions, relaxed trait bounds, macro Kleene matcher
`~` | Tilde | The tilde operator has been unused since before Rust 1.0, but its token may still be used.

## Comments

Comment | Use
--- | ---
`//` | line comment
`//!` | inner line comment
`///` | outer line doc comment
`/*…*/` | block comment
`/*!…*/` | inner block doc comment
`/**…*/` | outer block doc comment

## Other tokens

Token | Use
--- | ---
`ident` | identifiers
`r#ident` | raw identifiers
`'ident` | lifetimes and loop labels
`'r#ident` | raw lifetimes and loop labels
`…u8`, `…i32`, `…f64`, `…usize`, … | number literals
`"…"` | string literals
`r"…"`, `r#"…"#`, `r##"…"##`, … | raw string literals
`b"…"` | byte string literals
`br"…"`, `br#"…"#`, `br##"…"##`, … | raw byte string literals
`'…'` | character literals
`b'…'` | byte literals
`c"…"` | C string literals
`cr"…"`, `cr#"…"#`, `cr##"…"##`, … | raw C string literals

## Macros

Syntax | Use
--- | ---
`ident!(…)` `ident! {…}` `ident![…]` | macro invocations
`$ident` | macro metavariable
`$ident:kind` | macro matcher fragment specifier
`$(…)…` | macro repetition

## Attributes

Syntax | Use
--- | ---
`#[meta]` | outer attribute
`#![meta]` | inner attribute

## Expressions

Expression | Use
--- | ---
`|…| expr` `|…| -> Type { … }` | closures
`ident::…` | paths
`::crate_name::…` | explicit crate paths
`crate::…` | crate-relative paths
`self::…` | module-relative paths
`super::…` | parent module paths
`Type::…` `<Type as Trait>::ident` | associated items
`<Type>::…` | qualified paths which can be used for types without names such as `<&T>::…`, `<[T]>::…`, etc.
`Trait::method(…)` `Type::method(…)` `<Type as Trait>::method(…)` | disambiguated method calls
`method::<…>(…)` `path::<…>` | generic arguments, aka turbofish
`()` | unit
`(expr)` | parenthesized expressions
`(expr,)` | single-element tuple expressions
`(expr, …)` | tuple expressions
`expr(expr, …)` | call expressions
`expr.0`, `expr.1`, … | tuple indexing expressions
`expr.ident` | field access expressions
`{…}` | block expressions
`Type {…}` | struct expressions
`Type(…)` | tuple struct constructors
`[…]` | array expressions
`[expr; len]` | repeat array expressions
`expr[..]`, `expr[a..]`, `expr[..b]`, `expr[a..b]`, `expr[a..=b]`, `expr[..=b]` | array and slice indexing expressions
`if expr {…} else {…}` | if expressions
`match expr { pattern => {…} }` | match expressions
`loop {…}` | infinite loop expressions
`while expr {…}` | predicate loop expressions
`for pattern in expr {…}` | iterator loops
`&expr` `&mut expr` | borrow expressions
`&raw const expr` `&raw mut expr` | raw borrow expressions
`*expr` | dereference expressions
`expr?` | try propagation expressions
`-expr` | negation expressions
`!expr` | bitwise and logical NOT expressions
`expr as Type` | type cast expressions

## Items

Items are the components of a crate.

Item | Use
--- | ---
`mod ident;` `mod ident {…}` | modules
`use path;` | use declarations
`fn ident(…) {…}` | functions
`type Type = Type;` | type aliases
`struct ident {…}` | structs
`enum ident {…}` | enumerations
`union ident {…}` | unions
`trait ident {…}` | traits
`impl Type {…}` `impl Type for Trait {…}` | implementations
`const ident = expr;` | constant items
`static ident = expr;` | static items
`extern "C" {…}` | external blocks
`fn ident<…>(…) …` `struct ident<…> {…}` `enum ident<…> {…}` `impl<…> Type<…> {…}` | generic definitions

## Type expressions

Type expressions are used to refer to types.

Type | Use
--- | ---
`bool`, `u8`, `f64`, `str`, … | primitive types
`for<…>` | higher-ranked trait bounds
`T: TraitA + TraitB` | trait bounds
`T: 'a + 'b` | lifetime bounds
`T: TraitA + 'a` | trait and lifetime bounds
`T: ?Sized` | relaxed trait bounds
`[Type; len]` | array types
`(Type, …)` | tuple types
`[Type]` | slice types
`(Type)` | parenthesized types
`impl Trait` | impl trait types, anonymous type parameters
`dyn Trait` | trait object types
`ident` `ident::…` | type paths (can refer to structs, enumerations, unions, type aliases, traits, generics, etc.)
`Type<…>` `Trait<…>` | generic arguments (e.g. `Vec<u8>`)
`Trait<ident = Type>` | associated type bindings (e.g. `Iterator<Item = T>`)
`Trait<ident: …>` | associated type bounds (e.g. `Iterator<Item: Send>`)
`&Type` `&mut Type` | reference types
`*mut Type` `*const Type` | raw pointer types
`fn(…) -> Type` | function pointer types
`_` | inferred type, inferred const
`'_` | placeholder lifetime
`!` | never type

## Patterns

Patterns are used to match values.

Pattern | Use
--- | ---
`"foo"`, `'a'`, `123`, `2.4`, … | literal patterns
`ident` | identifier patterns
`_` | wildcard pattern
`..` | rest pattern
`a..`, `..b`, `a..b`, `a..=b`, `..=b` | range patterns
`&pattern` `&mut pattern` | reference patterns
`path {…}` | struct patterns
`path(…)` | tuple struct patterns
`(pattern, …)` | tuple patterns
`(pattern)` | grouped patterns
`[pattern, …]` | slice patterns
`CONST`, `Enum::Variant`, … | path patterns

[macro.ambiguity]

# Appendix: Macro follow-set ambiguity formal specification

This page documents the formal specification of the follow rules for Macros By Example. They were originally specified in RFC 550, from which the bulk of this text is copied, and expanded upon in subsequent RFCs.

[macro.ambiguity.convention]

## Definitions & conventions

[macro.ambiguity.convention.defs]

- `macro`: anything invocable as `foo!(...)` in source code.
- `MBE`: macro-by-example, a macro defined by `macro_rules`.
- `matcher`: the left-hand-side of a rule in a `macro_rules` invocation, or a subportion thereof.
- `macro parser`: the bit of code in the Rust parser that will parse the input using a grammar derived from all of the matchers.
- `fragment`: The class of Rust syntax that a given matcher will accept (or “match”).
- `repetition` : a fragment that follows a regular repeating pattern
- `NT`: non-terminal, the various “meta-variables” or repetition matchers that can appear in a matcher, specified in MBE syntax with a leading `$` character.
- `simple NT`: a “meta-variable” non-terminal (further discussion below).
- `complex NT`: a repetition matching non-terminal, specified via repetition operators (`*`, `+`, `?`).
- `token`: an atomic element of a matcher; i.e. identifiers, operators, open/close delimiters, and simple NT’s.
- `token tree`: a tree structure formed from tokens (the leaves), complex NT’s, and finite sequences of token trees.
- `delimiter token`: a token that is meant to divide the end of one fragment and the start of the next fragment.
- `separator token`: an optional delimiter token in an complex NT that separates each pair of elements in the matched repetition.
- `separated complex NT`: a complex NT that has its own separator token.
- `delimited sequence`: a sequence of token trees with appropriate open- and close-delimiters at the start and end of the sequence.
- `empty fragment`: The class of invisible Rust syntax that separates tokens, i.e. whitespace, or (in some lexical contexts), the empty token sequence.
- `fragment specifier`: The identifier in a simple NT that specifies which fragment the NT accepts.
- `language`: a context-free language.

Example:

    #![allow(unused)]
    fn main() {
    macro_rules! i_am_an_mbe {
        (start $foo:expr $($i:ident),* end) => ($foo)
    }
    }

[macro.ambiguity.convention.matcher]

`(start $foo:expr $($i:ident),* end)` is a matcher. The whole matcher is a delimited sequence (with open- and close-delimiters `(` and `)`), and `$foo` and `$i` are simple NT’s with `expr` and `ident` as their respective fragment specifiers.

[macro.ambiguity.convention.complex-nt]

`$(i:ident),*` is also an NT; it is a complex NT that matches a comma-separated repetition of identifiers. The `,` is the separator token for the complex NT; it occurs in between each pair of elements (if any) of the matched fragment.

Another example of a complex NT is `$(hi $e:expr ;)+`, which matches any fragment of the form `hi <expr>; hi <expr>; ...` where `hi <expr>;` occurs at least once. Note that this complex NT does not have a dedicated separator token.

(Note that Rust’s parser ensures that delimited sequences always occur with proper nesting of token tree structure and correct matching of open- and close-delimiters.)

[macro.ambiguity.convention.vars]

We will tend to use the variable “M” to stand for a matcher, variables “t” and “u” for arbitrary individual tokens, and the variables “tt” and “uu” for arbitrary token trees. (The use of “tt” does present potential ambiguity with its additional role as a fragment specifier; but it will be clear from context which interpretation is meant.)

[macro.ambiguity.convention.set]

“SEP” will range over separator tokens, “OP” over the repetition operators `*`, `+`, and `?`, “OPEN”/“CLOSE” over matching token pairs surrounding a delimited sequence (e.g. `[` and `]`).

[macro.ambiguity.convention.sequence-vars]

Greek letters “α” “β” “γ” “δ” stand for potentially empty token-tree sequences. (However, the Greek letter “ε” (epsilon) has a special role in the presentation and does not stand for a token-tree sequence.)

- This Greek letter convention is usually just employed when the presence of a sequence is a technical detail; in particular, when we wish to emphasize that we are operating on a sequence of token-trees, we will use the notation “tt …” for the sequence, not a Greek letter.

Note that a matcher is merely a token tree. A “simple NT”, as mentioned above, is an meta-variable NT; thus it is a non-repetition. For example, `$foo:ty` is a simple NT but `$($foo:ty)+` is a complex NT.

Note also that in the context of this formalism, the term “token” generally includes simple NTs.

Finally, it is useful for the reader to keep in mind that according to the definitions of this formalism, no simple NT matches the empty fragment, and likewise no token matches the empty fragment of Rust syntax. (Thus, the only NT that can match the empty fragment is a complex NT.) This is not actually true, because the `vis` matcher can match an empty fragment. Thus, for the purposes of the formalism, we will treat `$v:vis` as actually being `$($v:vis)?`, with a requirement that the matcher match an empty fragment.

[macro.ambiguity.invariant]

### The matcher invariants

[macro.ambiguity.invariant.list]

To be valid, a matcher must meet the following three invariants. The definitions of FIRST and FOLLOW are described later.

1. For any two successive token tree sequences in a matcher `M` (i.e. `M = ... tt uu ...`) with `uu ...` nonempty, we must have FOLLOW(`... tt`) ∪ {ε} ⊇ FIRST(`uu ...`).
2. For any separated complex NT in a matcher, `M = ... $(tt ...) SEP OP ...`, we must have `SEP` ∈ FOLLOW(`tt ...`).
3. For an unseparated complex NT in a matcher, `M = ... $(tt ...) OP ...`, if OP = `*` or `+`, we must have FOLLOW(`tt ...`) ⊇ FIRST(`tt ...`).

[macro.ambiguity.invariant.follow-matcher]

The first invariant says that whatever actual token that comes after a matcher, if any, must be somewhere in the predetermined follow set. This ensures that a legal macro definition will continue to assign the same determination as to where `... tt` ends and `uu ...` begins, even as new syntactic forms are added to the language.

[macro.ambiguity.invariant.separated-complex-nt]

The second invariant says that a separated complex NT must use a separator token that is part of the predetermined follow set for the internal contents of the NT. This ensures that a legal macro definition will continue to parse an input fragment into the same delimited sequence of `tt ...`’s, even as new syntactic forms are added to the language.

[macro.ambiguity.invariant.unseparated-complex-nt]

The third invariant says that when we have a complex NT that can match two or more copies of the same thing with no separation in between, it must be permissible for them to be placed next to each other as per the first invariant. This invariant also requires they be nonempty, which eliminates a possible ambiguity.

NOTE: The third invariant is currently unenforced due to historical oversight and significant reliance on the behaviour. It is currently undecided what to do about this going forward. Macros that do not respect the behaviour may become invalid in a future edition of Rust. See the tracking issue.

[macro.ambiguity.sets]

### FIRST and FOLLOW, informally

[macro.ambiguity.sets.intro]

A given matcher M maps to three sets: FIRST(M), LAST(M) and FOLLOW(M).

Each of the three sets is made up of tokens. FIRST(M) and LAST(M) may also contain a distinguished non-token element ε (“epsilon”), which indicates that M can match the empty fragment. (But FOLLOW(M) is always just a set of tokens.)

Informally:

[macro.ambiguity.sets.first]

- FIRST(M): collects the tokens potentially used first when matching a fragment to M.

[macro.ambiguity.sets.last]

- LAST(M): collects the tokens potentially used last when matching a fragment to M.

[macro.ambiguity.sets.follow]

- FOLLOW(M): the set of tokens allowed to follow immediately after some fragment matched by M.

  In other words: t ∈ FOLLOW(M) if and only if there exists (potentially empty) token sequences α, β, γ, δ where:

  - M matches β,

  - t matches γ, and

  - The concatenation α β γ δ is a parseable Rust program.

[macro.ambiguity.sets.universe]

We use the shorthand ANYTOKEN to denote the set of all tokens (including simple NTs). For example, if any token is legal after a matcher M, then FOLLOW(M) = ANYTOKEN.

(To review one’s understanding of the above informal descriptions, the reader at this point may want to jump ahead to the examples of FIRST/LAST before reading their formal definitions.)

[macro.ambiguity.sets.def]

### FIRST, LAST

[macro.ambiguity.sets.def.intro]

Below are formal inductive definitions for FIRST and LAST.

[macro.ambiguity.sets.def.notation]

“A ∪ B” denotes set union, “A ∩ B” denotes set intersection, and “A \ B” denotes set difference (i.e. all elements of A that are not present in B).

[macro.ambiguity.sets.def.first]

#### FIRST

[macro.ambiguity.sets.def.first.intro]

FIRST(M) is defined by case analysis on the sequence M and the structure of its first token-tree (if any):

[macro.ambiguity.sets.def.first.epsilon]

- if M is the empty sequence, then FIRST(M) = { ε },

[macro.ambiguity.sets.def.first.token]

- if M starts with a token t, then FIRST(M) = { t },

  (Note: this covers the case where M starts with a delimited token-tree sequence, `M = OPEN tt ... CLOSE ...`, in which case `t = OPEN` and thus FIRST(M) = { `OPEN` }.)

  (Note: this critically relies on the property that no simple NT matches the empty fragment.)

[macro.ambiguity.sets.def.first.complex]

- Otherwise, M is a token-tree sequence starting with a complex NT: `M = $( tt ... ) OP α`, or `M = $( tt ... ) SEP OP α`, (where `α` is the (potentially empty) sequence of token trees for the rest of the matcher).

  - Let SEP_SET(M) = { SEP } if SEP is present and ε ∈ FIRST(`tt ...`); otherwise SEP_SET(M) = {}.

- Let ALPHA_SET(M) = FIRST(`α`) if OP = `*` or `?` and ALPHA_SET(M) = {} if OP = `+`.

- FIRST(M) = (FIRST(`tt ...`) \ {ε}) ∪ SEP_SET(M) ∪ ALPHA_SET(M).

The definition for complex NTs deserves some justification. SEP_SET(M) defines the possibility that the separator could be a valid first token for M, which happens when there is a separator defined and the repeated fragment could be empty. ALPHA_SET(M) defines the possibility that the complex NT could be empty, meaning that M’s valid first tokens are those of the following token-tree sequences `α`. This occurs when either `*` or `?` is used, in which case there could be zero repetitions. In theory, this could also occur if `+` was used with a potentially-empty repeating fragment, but this is forbidden by the third invariant.

From there, clearly FIRST(M) can include any token from SEP_SET(M) or ALPHA_SET(M), and if the complex NT match is nonempty, then any token starting FIRST(`tt ...`) could work too. The last piece to consider is ε. SEP_SET(M) and FIRST(`tt ...`) \ {ε} cannot contain ε, but ALPHA_SET(M) could. Hence, this definition allows M to accept ε if and only if ε ∈ ALPHA_SET(M) does. This is correct because for M to accept ε in the complex NT case, both the complex NT and α must accept it. If OP = `+`, meaning that the complex NT cannot be empty, then by definition ε ∉ ALPHA_SET(M). Otherwise, the complex NT can accept zero repetitions, and then ALPHA_SET(M) = FOLLOW(`α`). So this definition is correct with respect to \varepsilon as well.

[macro.ambiguity.sets.def.last]

#### LAST

[macro.ambiguity.sets.def.last.intro]

LAST(M), defined by case analysis on M itself (a sequence of token-trees):

[macro.ambiguity.sets.def.last.empty]

- if M is the empty sequence, then LAST(M) = { ε }

[macro.ambiguity.sets.def.last.token]

- if M is a singleton token t, then LAST(M) = { t }

[macro.ambiguity.sets.def.last.rep-star]

- if M is the singleton complex NT repeating zero or more times, `M = $( tt ... ) *`, or `M = $( tt ... ) SEP *`

  - Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.

  - if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set

  - otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`) ∪ {ε}.

[macro.ambiguity.sets.def.last.rep-plus]

- if M is the singleton complex NT repeating one or more times, `M = $( tt ... ) +`, or `M = $( tt ... ) SEP +`

  - Let sep_set = { SEP } if SEP present; otherwise sep_set = {}.

  - if ε ∈ LAST(`tt ...`) then LAST(M) = LAST(`tt ...`) ∪ sep_set

  - otherwise, the sequence `tt ...` must be non-empty; LAST(M) = LAST(`tt ...`)

[macro.ambiguity.sets.def.last.rep-question]

- if M is the singleton complex NT repeating zero or one time, `M = $( tt ...) ?`, then LAST(M) = LAST(`tt ...`) ∪ {ε}.

[macro.ambiguity.sets.def.last.delim]

- if M is a delimited token-tree sequence `OPEN tt ... CLOSE`, then LAST(M) = { `CLOSE` }.

[macro.ambiguity.sets.def.last.sequence]

- if M is a non-empty sequence of token-trees `tt uu ...`,

  - If ε ∈ LAST(`uu ...`), then LAST(M) = LAST(`tt`) ∪ (LAST(`uu ...`) \ { ε }).

  - Otherwise, the sequence `uu ...` must be non-empty; then LAST(M) = LAST(`uu ...`).

### Examples of FIRST and LAST

Below are some examples of FIRST and LAST. (Note in particular how the special ε element is introduced and eliminated based on the interaction between the pieces of the input.)

Our first example is presented in a tree structure to elaborate on how the analysis of the matcher composes. (Some of the simpler subtrees have been elided.)

    INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
                ~~~~~~~~   ~~~~~~~                ~
                    |         |                   |
    FIRST:   { $d:ident }  { $e:expr }          { h }

    INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+
                ~~~~~~~~~~~~~~~~~~             ~~~~~~~           ~~~
                            |                      |               |
    FIRST:          { $d:ident }               { h, ε }         { f }

    INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~    ~~~~~~~~~~~~~~    ~~~~~~~~~   ~
                            |                       |              |       |
    FIRST:        { $d:ident, ε }            {  h, ε, ;  }      { f }   { g }

    INPUT:  $(  $d:ident   $e:expr   );*    $( $( h )* );*    $( f ; )+   g
            ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
                                            |
    FIRST:                       { $d:ident, h, ;,  f }

Thus:

- FIRST(`$($d:ident $e:expr );* $( $(h)* );* $( f ;)+ g`) = { `$d:ident`, `h`, `;`, `f` }

Note however that:

- FIRST(`$($d:ident $e:expr );* $( $(h)* );* $($( f ;)+ g)*`) = { `$d:ident`, `h`, `;`, `f`, ε }

Here are similar examples but now for LAST.

- LAST(`$d:ident $e:expr`) = { `$e:expr` }
- LAST(`$( $d:ident $e:expr );*`) = { `$e:expr`, ε }
- LAST(`$( $d:ident $e:expr );* $(h)*`) = { `$e:expr`, ε, `h` }
- LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+`) = { `;` }
- LAST(`$( $d:ident $e:expr );* $(h)* $( f ;)+ g`) = { `g` }

[macro.ambiguity.sets.def.follow]

### FOLLOW(M)

[macro.ambiguity.sets.def.follow.intro]

Finally, the definition for FOLLOW(M) is built up as follows. pat, expr, etc. represent simple nonterminals with the given fragment specifier.

[macro.ambiguity.sets.def.follow.pat]

- FOLLOW(pat) = {`=>`, `,`, `=`, `|`, `if`, `in`}`.

[macro.ambiguity.sets.def.follow.expr-stmt]

- FOLLOW(expr) = FOLLOW(expr_2021) = FOLLOW(stmt) = {`=>`, `,`, `;`}`.

[macro.ambiguity.sets.def.follow.ty-path]

- FOLLOW(ty) = FOLLOW(path) = {`{`, `[`, `,`, `=>`, `:`, `=`, `>`, `>>`, `;`, `|`, `as`, `where`, block nonterminals}.

[macro.ambiguity.sets.def.follow.vis]

- FOLLOW(vis) = {`,`l any keyword or identifier except a non-raw `priv`; any token that can begin a type; ident, ty, and path nonterminals}.

[macro.ambiguity.sets.def.follow.simple]

- FOLLOW(t) = ANYTOKEN for any other simple token, including block, ident, tt, item, lifetime, literal and meta simple nonterminals, and all terminals.

[macro.ambiguity.sets.def.follow.other-matcher]

- FOLLOW(M), for any other M, is defined as the intersection, as t ranges over (LAST(M) \ {ε}), of FOLLOW(t).

[macro.ambiguity.sets.def.follow.type-first]

The tokens that can begin a type are, as of this writing, {`(`, `[`, `!`, `*`, `&`, `&&`, `?`, lifetimes, `>`, `>>`, `::`, any non-keyword identifier, `super`, `self`, `Self`, `extern`, `crate`, `$crate`, `_`, `for`, `impl`, `fn`, `unsafe`, `typeof`, `dyn`}, although this list may not be complete because people won’t always remember to update the appendix when new ones are added.

Examples of FOLLOW for complex M:

- FOLLOW(`$( $d:ident $e:expr )*`) = FOLLOW(`$e:expr`)
- FOLLOW(`$( $d:ident $e:expr )* $(;)*`) = FOLLOW(`$e:expr`) ∩ ANYTOKEN = FOLLOW(`$e:expr`)
- FOLLOW(`$( $d:ident $e:expr )* $(;)* $( f |)+`) = ANYTOKEN

### Examples of valid and invalid matchers

With the above specification in hand, we can present arguments for why particular matchers are legal and others are not.

- `($ty:ty < foo ,)` : illegal, because FIRST(`< foo ,`) = { `<` } ⊈ FOLLOW(`ty`)

- `($ty:ty , foo <)` : legal, because FIRST(`, foo <`) = { `,` } is ⊆ FOLLOW(`ty`).

- `($pa:pat $pb:pat $ty:ty ,)` : illegal, because FIRST(`$pb:pat $ty:ty ,`) = { `$pb:pat` } ⊈ FOLLOW(`pat`), and also FIRST(`$ty:ty ,`) = { `$ty:ty` } ⊈ FOLLOW(`pat`).

- `( $($a:tt $b:tt)* ; )` : legal, because FIRST(`$b:tt`) = { `$b:tt` } is ⊆ FOLLOW(`tt`) = ANYTOKEN, as is FIRST(`;`) = { `;` }.

- `( $($t:tt),* , $(t:tt),* )` : legal, (though any attempt to actually use this macro will signal a local ambiguity error during expansion).

- `($ty:ty $(; not sep)* -)` : illegal, because FIRST(`$(; not sep)* -`) = { `;`, `-` } is not in FOLLOW(`ty`).

- `($($ty:ty)-+)` : illegal, because separator `-` is not in FOLLOW(`ty`).

- `($($e:expr)*)` : illegal, because expr NTs are not in FOLLOW(expr NT).

# Influences

Rust is not a particularly original language, with design elements coming from a wide range of sources. Some of these are listed below (including elements that have since been removed):

- SML, OCaml: algebraic data types, pattern matching, type inference, semicolon statement separation
- C++: references, RAII, smart pointers, move semantics, monomorphization, memory model
- ML Kit, Cyclone: region based memory management
- Haskell (GHC): typeclasses, type families
- Newsqueak, Alef, Limbo: channels, concurrency
- Erlang: message passing, thread failure, linked thread failure, lightweight concurrency
- Swift: optional bindings
- Scheme: hygienic macros
- C#: attributes
- Ruby: closure syntax, block syntax
- NIL, Hermes: typestate
- Unicode Annex #31: identifier and pattern syntax

# Test summary

The following is a summary of the total tests that are linked to individual rule identifiers within the reference.

| Rules | Tests | Uncovered Rules | Coverage
--- | --- | --- | --- | ---
Introduction | 1 | 0 | 1 Uncovered rules example.rule.label | 0.0%
1. Notation | 5 | 0 | 5 Uncovered rules notation notation.grammar notation.grammar.string-tables notation.grammar.syntax notation.grammar.visualizations | 0.0%
2. Lexical structure | 0 |  |  |
2.1. Input format | 12 | 21 | 6 Uncovered rules input input.encoding input.intro input.shebang.intro input.syntax input.tokenization | 50.0%
2.2. Keywords | 18 | 0 | 18 Uncovered rules lex.keywords lex.keywords.reserved lex.keywords.reserved.edition2018 lex.keywords.reserved.edition2024 lex.keywords.reserved.intro lex.keywords.reserved.list lex.keywords.strict lex.keywords.strict.edition2018 lex.keywords.strict.intro lex.keywords.strict.list lex.keywords.weak lex.keywords.weak.dyn.edition2018 lex.keywords.weak.intro lex.keywords.weak.lifetime-static lex.keywords.weak.macro_rules lex.keywords.weak.raw lex.keywords.weak.safe lex.keywords.weak.union | 0.0%
2.3. Identifiers | 12 | 2 | 10 Uncovered rules ident ident.ascii-limitations ident.keyword ident.profile ident.raw ident.raw.allowed ident.raw.intro ident.raw.reserved ident.syntax ident.zero-width-chars | 16.7%
2.4. Comments | 10 | 0 | 10 Uncovered rules comments comments.doc comments.doc.attributes comments.doc.bare-crs comments.doc.inner-attributes comments.doc.inner-syntax comments.doc.syntax comments.normal comments.normal.tokenization comments.syntax | 0.0%
2.5. Whitespace | 5 | 0 | 5 Uncovered rules lex.whitespace lex.whitespace.intro lex.whitespace.replacement lex.whitespace.token-sep whitespace.syntax | 0.0%
2.6. Tokens | 116 | 0 | 116 Uncovered rules lex.token lex.token.byte lex.token.byte.intro lex.token.byte.syntax lex.token.delim lex.token.intro lex.token.life lex.token.life.intro lex.token.life.raw.allowed lex.token.life.raw.edition2021 lex.token.life.raw.intro lex.token.life.raw.reserved lex.token.life.syntax lex.token.literal lex.token.literal.char lex.token.literal.char-escape lex.token.literal.char-escape.ascii lex.token.literal.char-escape.intro lex.token.literal.char-escape.null lex.token.literal.char-escape.slash lex.token.literal.char-escape.unicode lex.token.literal.char-escape.whitespace lex.token.literal.char.intro lex.token.literal.char.syntax lex.token.literal.float lex.token.literal.float.form lex.token.literal.float.suffix lex.token.literal.float.syntax lex.token.literal.int lex.token.literal.int.kind lex.token.literal.int.kind-bin lex.token.literal.int.kind-dec lex.token.literal.int.kind-hex lex.token.literal.int.kind-oct lex.token.literal.int.restriction lex.token.literal.int.syntax lex.token.literal.int.tuple-field lex.token.literal.int.tuple-field.eq lex.token.literal.int.tuple-field.intro lex.token.literal.int.tuple-field.syntax lex.token.literal.literal.suffix.intro lex.token.literal.num lex.token.literal.reserved lex.token.literal.reserved.empty-exp lex.token.literal.reserved.empty-with-radix lex.token.literal.reserved.exp lex.token.literal.reserved.intro lex.token.literal.reserved.out-of-range lex.token.literal.reserved.period lex.token.literal.reserved.syntax lex.token.literal.str lex.token.literal.str-byte-raw.content lex.token.literal.str-raw lex.token.literal.str-raw.body lex.token.literal.str-raw.content lex.token.literal.str-raw.intro lex.token.literal.str-raw.syntax lex.token.literal.str.intro lex.token.literal.str.linefeed lex.token.literal.str.syntax lex.token.literal.suffix lex.token.literal.suffix.parse lex.token.literal.suffix.syntax lex.token.literal.suffix.validity lex.token.punct lex.token.punct.intro lex.token.punct.syntax lex.token.reserved lex.token.reserved-guards lex.token.reserved-guards.edition2024 lex.token.reserved-guards.intro lex.token.reserved-guards.pounds lex.token.reserved-guards.string-literal lex.token.reserved-guards.syntax lex.token.reserved-prefix lex.token.reserved-prefix.edition2021 lex.token.reserved-prefix.id lex.token.reserved-prefix.intro lex.token.reserved-prefix.life lex.token.reserved-prefix.raw-token lex.token.reserved-prefix.strings lex.token.reserved-prefix.syntax lex.token.reserved.intro lex.token.reserved.syntax lex.token.str-byte lex.token.str-byte-raw lex.token.str-byte-raw.body lex.token.str-byte-raw.intro lex.token.str-byte-raw.syntax lex.token.str-byte.escape lex.token.str-byte.escape-byte lex.token.str-byte.escape-null lex.token.str-byte.escape-slash lex.token.str-byte.escape-whitespace lex.token.str-byte.intro lex.token.str-byte.linefeed lex.token.str-byte.syntax lex.token.str-c lex.token.str-c-raw lex.token.str-c-raw.body lex.token.str-c-raw.content lex.token.str-c-raw.edition2021 lex.token.str-c-raw.intro lex.token.str-c-raw.syntax lex.token.str-c.char-unicode lex.token.str-c.edition2021 lex.token.str-c.escape lex.token.str-c.escape-byte lex.token.str-c.escape-slash lex.token.str-c.escape-unicode lex.token.str-c.escape-whitespace lex.token.str-c.intro lex.token.str-c.linefeed lex.token.str-c.null lex.token.str-c.syntax lex.token.syntax | 0.0%
3. Macros | 13 | 0 | 13 Uncovered rules macro macro.intro macro.invocation macro.invocation.expr macro.invocation.extern macro.invocation.intro macro.invocation.item macro.invocation.item-statement macro.invocation.name-resolution macro.invocation.nested macro.invocation.pattern macro.invocation.syntax macro.invocation.type | 0.0%
3.1. Macros by example | 65 | 0 | 65 Uncovered rules macro.decl macro.decl.follow-set macro.decl.follow-set.edition2021 macro.decl.follow-set.intro macro.decl.follow-set.repetition macro.decl.follow-set.token-expr-stmt macro.decl.follow-set.token-other macro.decl.follow-set.token-pat macro.decl.follow-set.token-pat_param macro.decl.follow-set.token-path-ty macro.decl.follow-set.token-restriction macro.decl.follow-set.token-vis macro.decl.hygiene macro.decl.hygiene.crate macro.decl.hygiene.intro macro.decl.hygiene.vis macro.decl.intro macro.decl.meta macro.decl.meta.dollar-crate macro.decl.meta.edition2021 macro.decl.meta.edition2024 macro.decl.meta.intro macro.decl.meta.specifier macro.decl.meta.transcription macro.decl.repetition macro.decl.repetition.fragment macro.decl.repetition.intro macro.decl.repetition.operators macro.decl.repetition.optional-restriction macro.decl.repetition.separator macro.decl.scope macro.decl.scope.intro macro.decl.scope.macro_export macro.decl.scope.macro_export.allowed-positions macro.decl.scope.macro_export.duplicates macro.decl.scope.macro_export.export macro.decl.scope.macro_export.intro macro.decl.scope.macro_export.local_inner_macros macro.decl.scope.macro_export.macro_use macro.decl.scope.macro_export.path-based macro.decl.scope.macro_export.syntax macro.decl.scope.macro_use macro.decl.scope.macro_use.allowed-positions macro.decl.scope.macro_use.duplicates macro.decl.scope.macro_use.export macro.decl.scope.macro_use.extern-crate-self macro.decl.scope.macro_use.intro macro.decl.scope.macro_use.mod-decl macro.decl.scope.macro_use.prelude macro.decl.scope.macro_use.syntax macro.decl.scope.path-based macro.decl.scope.path-based.intro macro.decl.scope.path-based.visibility macro.decl.scope.path.reexport macro.decl.scope.textual macro.decl.scope.textual.intro macro.decl.scope.textual.shadow macro.decl.scope.textual.shadow.path-based macro.decl.scope.unqualified macro.decl.syntax macro.decl.transcription macro.decl.transcription.fragment macro.decl.transcription.intro macro.decl.transcription.lookahead macro.decl.transcription.syntax | 0.0%
3.2. Procedural macros | 45 | 0 | 45 Uncovered rules macro.proc macro.proc.attribute macro.proc.attribute.allowed-positions macro.proc.attribute.behavior macro.proc.attribute.duplicates macro.proc.attribute.intro macro.proc.attribute.namespace macro.proc.attribute.syntax macro.proc.attribute.use-positions macro.proc.def macro.proc.derive macro.proc.derive.allowed-positions macro.proc.derive.attributes macro.proc.derive.attributes.decl macro.proc.derive.attributes.intro macro.proc.derive.attributes.scope macro.proc.derive.duplicates macro.proc.derive.intro macro.proc.derive.namespace macro.proc.derive.output macro.proc.derive.syntax macro.proc.error macro.proc.hygiene macro.proc.intro macro.proc.proc_macro macro.proc.proc_macro-crate macro.proc.proc_macro-crate.intro macro.proc.proc_macro-crate.span macro.proc.proc_macro-crate.token-stream macro.proc.proc_macro.allowed-positions macro.proc.proc_macro.behavior macro.proc.proc_macro.duplicates macro.proc.proc_macro.intro macro.proc.proc_macro.invocation macro.proc.proc_macro.namespace macro.proc.proc_macro.syntax macro.proc.result macro.proc.token macro.proc.token.conversion.from-proc_macro macro.proc.token.conversion.intro macro.proc.token.conversion.to-proc_macro macro.proc.token.doc-comment macro.proc.token.intro macro.proc.token.macro_rules macro.proc.token.tree | 0.0%
4. Crates and source files | 19 | 0 | 19 Uncovered rules crate crate.attributes crate.compile-time crate.crate_name crate.crate_name.general crate.crate_name.restriction crate.inline-module crate.input-source crate.items crate.main crate.main.general crate.main.import crate.main.restriction crate.module crate.module-def crate.no_main crate.syntax crate.uncaught-foreign-unwinding crate.unit | 0.0%
5. Conditional compilation | 75 | 0 | 75 Uncovered rules cfg cfg.attr cfg.attr.allowed-positions cfg.attr.crate-level-attrs cfg.attr.duplicates cfg.attr.effect cfg.attr.intro cfg.attr.syntax cfg.attributes-macro cfg.cfg_attr cfg.cfg_attr.allowed-positions cfg.cfg_attr.attr-restriction cfg.cfg_attr.attribute-list cfg.cfg_attr.behavior cfg.cfg_attr.duplicates cfg.cfg_attr.intro cfg.cfg_attr.syntax cfg.conditional cfg.debug_assertions cfg.general cfg.macro cfg.option-key-uniqueness cfg.option-key-value cfg.option-name cfg.option-spec cfg.options.crate cfg.options.general cfg.options.other cfg.options.set cfg.options.target cfg.panic cfg.panic.general cfg.panic.values cfg.predicate cfg.predicate.all cfg.predicate.any cfg.predicate.literal cfg.predicate.not cfg.predicate.option cfg.proc_macro cfg.syntax cfg.target_abi cfg.target_abi.disambiguation cfg.target_abi.general cfg.target_abi.values cfg.target_arch cfg.target_arch.gen cfg.target_arch.values cfg.target_endian cfg.target_env cfg.target_env.general cfg.target_env.values cfg.target_family cfg.target_family.general cfg.target_family.unix cfg.target_family.values cfg.target_family.windows cfg.target_feature cfg.target_feature.crt_static cfg.target_feature.general cfg.target_feature.values cfg.target_has_atomic cfg.target_has_atomic.general cfg.target_has_atomic.stdlib cfg.target_has_atomic.values cfg.target_os cfg.target_os.general cfg.target_os.values cfg.target_pointer_width cfg.target_pointer_width.general cfg.target_pointer_width.values cfg.target_vendor cfg.target_vendor.general cfg.target_vendor.values cfg.test | 0.0%
6. Items | 10 | 0 | 10 Uncovered rules items items.associated-locations items.decl-order items.extern-locations items.intro items.kinds items.locations items.name-resolution items.static-def items.syntax | 0.0%
6.1. Modules | 19 | 0 | 19 Uncovered rules items.mod items.mod.attributes items.mod.attributes.intro items.mod.attributes.supported items.mod.def items.mod.intro items.mod.multiple-items items.mod.namespace items.mod.nesting items.mod.outlined items.mod.outlined.intro items.mod.outlined.path items.mod.outlined.path.intro items.mod.outlined.path.search items.mod.outlined.path.search-nested items.mod.outlined.search items.mod.outlined.search-mod items.mod.syntax items.mod.unsafe | 0.0%
6.2. Extern crates | 17 | 0 | 17 Uncovered rules items.extern-crate items.extern-crate.as items.extern-crate.extern-prelude items.extern-crate.intro items.extern-crate.lookup items.extern-crate.name-restrictions items.extern-crate.namespace items.extern-crate.no_link items.extern-crate.no_link.allowed-positions items.extern-crate.no_link.duplicates items.extern-crate.no_link.intro items.extern-crate.no_link.syntax items.extern-crate.self items.extern-crate.syntax items.extern-crate.underscore items.extern-crate.underscore.intro items.extern-crate.underscore.macro_use | 0.0%
6.3. Use declarations | 41 | 0 | 41 Uncovered rules items.use items.use.as items.use.as-underscore items.use.as-underscore.glob items.use.as-underscore.intro items.use.as-underscore.macro items.use.forms items.use.forms.as items.use.forms.glob items.use.forms.multiple items.use.forms.nesting items.use.forms.self items.use.glob items.use.glob.edition2018 items.use.glob.intro items.use.glob.last-segment-only items.use.glob.self-import items.use.glob.shadowing items.use.intro items.use.multiple-syntax items.use.multiple-syntax.edition2018 items.use.multiple-syntax.empty items.use.multiple-syntax.intro items.use.path items.use.path.disallowed items.use.path.edition2018 items.use.path.intro items.use.path.namespace items.use.restrictions items.use.restrictions.crate items.use.restrictions.duplicate-name items.use.restrictions.macro-crate items.use.restrictions.self items.use.restrictions.variant items.use.self items.use.self.intro items.use.self.namespace items.use.syntax items.use.visibility items.use.visibility.intro items.use.visibility.unambiguous | 0.0%
6.4. Functions | 49 | 0 | 49 Uncovered rules items.fn items.fn.async items.fn.async.desugar items.fn.async.desugar-brief items.fn.async.edition2018 items.fn.async.future items.fn.async.intro items.fn.async.lifetime-capture items.fn.async.param-capture items.fn.async.safety items.fn.async.safety.intro items.fn.attributes items.fn.attributes.builtin-attributes items.fn.attributes.intro items.fn.body items.fn.body.bodyless items.fn.body.intro items.fn.const items.fn.extern items.fn.extern.abort items.fn.extern.def items.fn.extern.default-abi items.fn.extern.default-extern items.fn.extern.foreign-call items.fn.extern.intro items.fn.extern.unwind items.fn.extern.unwind.behavior items.fn.extern.unwind.intro items.fn.fn-item-type items.fn.generics items.fn.generics.explicit-arguments items.fn.generics.intro items.fn.generics.mono items.fn.generics.param-bounds items.fn.generics.param-names items.fn.implicit-return items.fn.intro items.fn.namespace items.fn.param-attributes items.fn.param-attributes.intro items.fn.param-attributes.parsed-attributes items.fn.params items.fn.params.intro items.fn.params.self-pat items.fn.params.self-restriction items.fn.params.varargs items.fn.safety-qualifiers items.fn.signature items.fn.syntax | 0.0%
6.5. Type aliases | 8 | 0 | 8 Uncovered rules items.type items.type.associated-impl items.type.associated-trait items.type.associated-type items.type.constructor-alias items.type.deprecated items.type.intro items.type.syntax | 0.0%
6.6. Structs | 7 | 0 | 7 Uncovered rules items.struct items.struct.intro items.struct.layout items.struct.namespace items.struct.syntax items.struct.tuple items.struct.unit | 0.0%
6.7. Enumerations | 33 | 0 | 33 Uncovered rules items.enum items.enum.constructor items.enum.constructor-names items.enum.constructor-namespace items.enum.decl items.enum.discriminant items.enum.discriminant.access-memory items.enum.discriminant.access-opaque items.enum.discriminant.coercion items.enum.discriminant.coercion.fieldless items.enum.discriminant.coercion.intro items.enum.discriminant.explicit items.enum.discriminant.explicit.intro items.enum.discriminant.explicit.primitive-repr items.enum.discriminant.explicit.unit-only items.enum.discriminant.implicit items.enum.discriminant.intro items.enum.discriminant.repr-rust items.enum.discriminant.restrictions items.enum.discriminant.restrictions.above-max-discriminant items.enum.discriminant.restrictions.same-discriminant items.enum.empty items.enum.empty.intro items.enum.empty.uninhabited items.enum.fieldless items.enum.intro items.enum.namespace items.enum.path-expr items.enum.struct-expr items.enum.syntax items.enum.tuple-expr items.enum.unit-only items.enum.variant-visibility | 0.0%
6.8. Unions | 31 | 0 | 31 Uncovered rules items.union items.union.common-storage items.union.drop items.union.field-copy items.union.field-manually-drop items.union.field-references items.union.field-restrictions items.union.field-tuple items.union.fieldless items.union.fields items.union.fields.intro items.union.fields.offset items.union.fields.read items.union.fields.read-safety items.union.fields.validity items.union.fields.write-safety items.union.init items.union.init.intro items.union.init.result items.union.intro items.union.namespace items.union.pattern items.union.pattern.intro items.union.pattern.one-field items.union.pattern.safety items.union.pattern.subpattern items.union.ref items.union.ref.borrow items.union.ref.intro items.union.ref.usage items.union.syntax | 0.0%
6.9. Constant items | 13 | 0 | 13 Uncovered rules items.const items.const.behavior items.const.destructor items.const.eval items.const.expr-omission items.const.intro items.const.namespace items.const.static items.const.static-temporary items.const.syntax items.const.unnamed items.const.unnamed.intro items.const.unnamed.repetition | 0.0%
6.10. Static items | 19 | 0 | 19 Uncovered rules items.static items.static.alternate items.static.generics items.static.init items.static.init.omission items.static.intro items.static.lifetime items.static.mut items.static.mut.extern items.static.mut.intro items.static.mut.safety items.static.mut.sync items.static.namespace items.static.read-only items.static.safety items.static.safety-qualifiers items.static.storage-disjointness items.static.sync items.static.syntax | 0.0%
6.11. Traits | 32 | 0 | 32 Uncovered rules items.traits items.traits.associated-item-decls items.traits.associated-item-namespaces items.traits.associated-visibility items.traits.associated-visibility.intro items.traits.bounds items.traits.const-fn items.traits.dyn-compatible items.traits.dyn-compatible.associated-consts items.traits.dyn-compatible.associated-functions items.traits.dyn-compatible.associated-types items.traits.dyn-compatible.async-traits items.traits.dyn-compatible.intro items.traits.dyn-compatible.sized items.traits.dyn-compatible.supertraits items.traits.generic items.traits.impls items.traits.intro items.traits.namespace items.traits.params items.traits.params.pattern-required.edition2018 items.traits.params.patterns-no-body items.traits.params.patterns-with-body items.traits.params.restriction-patterns.edition2018 items.traits.safety items.traits.safety.intro items.traits.self-param items.traits.supertraits items.traits.supertraits.decl items.traits.supertraits.intro items.traits.supertraits.subtrait items.traits.syntax | 0.0%
6.12. Implementations | 31 | 0 | 31 Uncovered rules items.impl items.impl.attributes items.impl.generics items.impl.generics.constrain items.impl.generics.intro items.impl.generics.usage items.impl.inherent items.impl.inherent.associated-item-path items.impl.inherent.associated-items items.impl.inherent.associated-items.allowed-items items.impl.inherent.coherence items.impl.inherent.implementing-type items.impl.inherent.intro items.impl.inherent.type-alias items.impl.intro items.impl.kinds items.impl.syntax items.impl.trait items.impl.trait.associated-item-path items.impl.trait.coherence items.impl.trait.coherence.intro items.impl.trait.coherence.overlapping items.impl.trait.def-requirement items.impl.trait.fundamental items.impl.trait.implemented-trait items.impl.trait.intro items.impl.trait.orphan-rule items.impl.trait.orphan-rule.general items.impl.trait.orphan-rule.intro items.impl.trait.safety items.impl.trait.uncovered-param | 0.0%
6.13. External blocks | 91 | 0 | 91 Uncovered rules items.extern items.extern.abi items.extern.abi.aapcs items.extern.abi.c items.extern.abi.cdecl items.extern.abi.default items.extern.abi.efiapi items.extern.abi.fastcall items.extern.abi.intro items.extern.abi.platform items.extern.abi.platform-unwind-variants items.extern.abi.rust items.extern.abi.standard items.extern.abi.stdcall items.extern.abi.system items.extern.abi.sysv64 items.extern.abi.thiscall items.extern.abi.unwind items.extern.abi.win64 items.extern.allowed-kinds items.extern.attributes items.extern.attributes.fn-parameters items.extern.attributes.intro items.extern.attributes.link items.extern.attributes.link.dylib items.extern.attributes.link.empty-block items.extern.attributes.link.framework items.extern.attributes.link.import_name_type items.extern.attributes.link.import_name_type.default items.extern.attributes.link.import_name_type.intro items.extern.attributes.link.import_name_type.platform-specific items.extern.attributes.link.import_name_type.values items.extern.attributes.link.import_name_type.variables items.extern.attributes.link.intro items.extern.attributes.link.kind-raw-dylib items.extern.attributes.link.kind-raw-dylib.import items.extern.attributes.link.kind-raw-dylib.intro items.extern.attributes.link.kind-raw-dylib.platform-specific items.extern.attributes.link.modifiers items.extern.attributes.link.modifiers.bundle items.extern.attributes.link.modifiers.bundle.allowed-kinds items.extern.attributes.link.modifiers.bundle.behavior items.extern.attributes.link.modifiers.bundle.behavior-negative items.extern.attributes.link.modifiers.bundle.default items.extern.attributes.link.modifiers.bundle.no-effect items.extern.attributes.link.modifiers.multiple items.extern.attributes.link.modifiers.syntax items.extern.attributes.link.modifiers.verbatim items.extern.attributes.link.modifiers.verbatim.allowed-kinds items.extern.attributes.link.modifiers.verbatim.behavior items.extern.attributes.link.modifiers.verbatim.behavior-negative items.extern.attributes.link.modifiers.verbatim.default items.extern.attributes.link.modifiers.whole-archive items.extern.attributes.link.modifiers.whole-archive.allowed-kinds items.extern.attributes.link.modifiers.whole-archive.behavior items.extern.attributes.link.modifiers.whole-archive.default items.extern.attributes.link.name-requirement items.extern.attributes.link.raw-dylib items.extern.attributes.link.static items.extern.attributes.link.syntax items.extern.attributes.link.wasm_import_module items.extern.attributes.link_name items.extern.attributes.link_name.allowed-positions items.extern.attributes.link_name.duplicates items.extern.attributes.link_name.intro items.extern.attributes.link_name.link_ordinal items.extern.attributes.link_name.syntax items.extern.attributes.link_ordinal items.extern.attributes.link_ordinal.allowed-kinds items.extern.attributes.link_ordinal.exclusive items.extern.attributes.link_ordinal.intro items.extern.edition2024 items.extern.fn items.extern.fn.body items.extern.fn.fn-ptr items.extern.fn.foreign-abi items.extern.fn.param-patterns items.extern.fn.qualifiers items.extern.fn.safety items.extern.intro items.extern.namespace items.extern.safety items.extern.static items.extern.static.intro items.extern.static.mut items.extern.static.read-only items.extern.static.safety items.extern.syntax items.extern.unsafe-required items.extern.variadic items.extern.variadic.conventions | 0.0%
6.14. Generic parameters | 26 | 2 | 24 Uncovered rules items.generics items.generics.attributes items.generics.builtin-generic-types items.generics.const items.generics.const.allowed-types items.generics.const.argument items.generics.const.argument.const-expr items.generics.const.exhaustiveness items.generics.const.inferred.constraint items.generics.const.intro items.generics.const.namespace items.generics.const.standalone items.generics.const.type-ambiguity items.generics.const.usage items.generics.const.variance items.generics.invalid-lifetimes items.generics.syntax items.generics.syntax.duplicate-params items.generics.syntax.intro items.generics.syntax.scope items.generics.where items.generics.where.higher-ranked-lifetimes items.generics.where.intro items.generics.where.syntax | 7.7%
6.15. Associated items | 45 | 0 | 45 Uncovered rules associated.fn.method.self-pat-mut associated.fn.method.self-pat-shorthands items.associated items.associated.const items.associated.const.decl items.associated.const.def items.associated.const.eval items.associated.const.intro items.associated.const.name items.associated.decl-def items.associated.fn items.associated.fn.decl items.associated.fn.def items.associated.fn.intro items.associated.fn.method items.associated.fn.method.intro items.associated.fn.method.self-ty items.associated.fn.param-attributes items.associated.fn.params.edition2018 items.associated.fn.qualified-self items.associated.intro items.associated.kinds items.associated.name items.associated.related items.associated.same-signature items.associated.syntax items.associated.trait-items items.associated.type items.associated.type.alias items.associated.type.decl items.associated.type.def items.associated.type.def.restriction items.associated.type.generic items.associated.type.generic-where-clause items.associated.type.generic-where-clause.forward items.associated.type.generic-where-clause.intersection items.associated.type.generic-where-clause.intro items.associated.type.generic-where-clause.static items.associated.type.generic-where-clause.valid-fn items.associated.type.impl-fulfillment items.associated.type.intro items.associated.type.name items.associated.type.param items.associated.type.restrictions items.associated.type.sized | 0.0%
7. Attributes | 24 | 0 | 24 Uncovered rules attributes attributes.activity attributes.activity.intro attributes.allowed-position attributes.builtin attributes.inner attributes.input attributes.intro attributes.kind attributes.meta attributes.meta.builtin attributes.meta.builtin.syntax attributes.meta.intro attributes.meta.literal-expr attributes.meta.order attributes.meta.order-macro attributes.meta.syntax attributes.outer attributes.safety attributes.syntax attributes.tool attributes.tool.ignored attributes.tool.intro attributes.tool.prelude | 0.0%
7.1. Testing | 23 | 0 | 23 Uncovered rules attributes.testing attributes.testing.ignore attributes.testing.ignore.allowed-positions attributes.testing.ignore.behavior attributes.testing.ignore.duplicates attributes.testing.ignore.intro attributes.testing.ignore.reason attributes.testing.ignore.syntax attributes.testing.should_panic attributes.testing.should_panic.allowed-positions attributes.testing.should_panic.duplicates attributes.testing.should_panic.expected attributes.testing.should_panic.intro attributes.testing.should_panic.return attributes.testing.should_panic.syntax attributes.testing.test attributes.testing.test.allowed-positions attributes.testing.test.duplicates attributes.testing.test.enabled attributes.testing.test.intro attributes.testing.test.stdlib attributes.testing.test.success attributes.testing.test.syntax | 0.0%
7.2. Derive | 15 | 0 | 15 Uncovered rules attributes.derive attributes.derive.allowed-positions attributes.derive.automatically_derived attributes.derive.automatically_derived.allowed-positions attributes.derive.automatically_derived.behavior attributes.derive.automatically_derived.duplicates attributes.derive.automatically_derived.intro attributes.derive.automatically_derived.syntax attributes.derive.behavior attributes.derive.built-in attributes.derive.built-in-automatically_derived attributes.derive.duplicates attributes.derive.intro attributes.derive.stdlib attributes.derive.syntax | 0.0%
7.3. Diagnostics | 51 | 30 | 38 Uncovered rules attributes.diagnostic.deprecated.allowed-positions attributes.diagnostic.do_not_recommend attributes.diagnostic.namespace attributes.diagnostic.namespace.intro attributes.diagnostic.on_unimplemented attributes.diagnostic.on_unimplemented.allowed-positions attributes.diagnostic.on_unimplemented.format-string attributes.diagnostics attributes.diagnostics.deprecated attributes.diagnostics.deprecated.intro attributes.diagnostics.deprecated.syntax attributes.diagnostics.expect attributes.diagnostics.expect.fulfillment attributes.diagnostics.expect.independent attributes.diagnostics.expect.intro attributes.diagnostics.lint attributes.diagnostics.lint.allow attributes.diagnostics.lint.deny attributes.diagnostics.lint.expect attributes.diagnostics.lint.forbid attributes.diagnostics.lint.group attributes.diagnostics.lint.group.warnings attributes.diagnostics.lint.level attributes.diagnostics.lint.override attributes.diagnostics.lint.reason attributes.diagnostics.lint.tool attributes.diagnostics.lint.tool.activation attributes.diagnostics.lint.tool.intro attributes.diagnostics.lint.warn attributes.diagnostics.must_use attributes.diagnostics.must_use.allowed-positions attributes.diagnostics.must_use.fn attributes.diagnostics.must_use.intro attributes.diagnostics.must_use.message attributes.diagnostics.must_use.trait attributes.diagnostics.must_use.trait-function attributes.diagnostics.must_use.trait-impl-function attributes.diagnostics.must_use.type | 25.5%
7.4. Code generation | 67 | 2 | 65 Uncovered rules attributes.codegen attributes.codegen.cold attributes.codegen.cold.allowed-positions attributes.codegen.cold.duplicates attributes.codegen.cold.syntax attributes.codegen.inline attributes.codegen.inline.allowed-positions attributes.codegen.inline.async attributes.codegen.inline.duplicates attributes.codegen.inline.externally-exported attributes.codegen.inline.intro attributes.codegen.inline.modes attributes.codegen.inline.syntax attributes.codegen.inline.trait attributes.codegen.instruction_set attributes.codegen.instruction_set.allowed-positions attributes.codegen.instruction_set.arm attributes.codegen.instruction_set.duplicates attributes.codegen.instruction_set.inline-asm attributes.codegen.instruction_set.intro attributes.codegen.instruction_set.syntax attributes.codegen.instruction_set.target-limits attributes.codegen.naked attributes.codegen.naked.body attributes.codegen.naked.call-stack attributes.codegen.naked.inline attributes.codegen.naked.intro attributes.codegen.naked.no-duplication attributes.codegen.naked.prologue-epilogue attributes.codegen.naked.testing attributes.codegen.naked.track_caller attributes.codegen.naked.unsafe-attribute attributes.codegen.naked.unused-variables attributes.codegen.no_builtins attributes.codegen.no_builtins.allowed-positions attributes.codegen.no_builtins.duplicates attributes.codegen.no_builtins.intro attributes.codegen.no_builtins.syntax attributes.codegen.target_feature attributes.codegen.target_feature.aarch64 attributes.codegen.target_feature.allowed-positions attributes.codegen.target_feature.arch attributes.codegen.target_feature.availability attributes.codegen.target_feature.closures attributes.codegen.target_feature.fn-traits attributes.codegen.target_feature.info attributes.codegen.target_feature.inline attributes.codegen.target_feature.intro attributes.codegen.target_feature.loongarch attributes.codegen.target_feature.remark-cfg attributes.codegen.target_feature.remark-rt attributes.codegen.target_feature.riscv attributes.codegen.target_feature.s390x attributes.codegen.target_feature.safety-restrictions attributes.codegen.target_feature.target-ub attributes.codegen.target_feature.wasm attributes.codegen.target_feature.x86 attributes.codegen.track_caller attributes.codegen.track_caller.allowed-positions attributes.codegen.track_caller.behavior attributes.codegen.track_caller.decay attributes.codegen.track_caller.extern attributes.codegen.track_caller.hint attributes.codegen.track_caller.limits attributes.codegen.track_caller.traits | 3.0%
7.5. Limits | 9 | 0 | 9 Uncovered rules attributes.limits attributes.limits.recursion_limit attributes.limits.recursion_limit.intro attributes.limits.recursion_limit.syntax attributes.limits.type_length_limit attributes.limits.type_length_limit.allowed-positions attributes.limits.type_length_limit.duplicates attributes.limits.type_length_limit.intro attributes.limits.type_length_limit.syntax | 0.0%
7.6. Type system | 9 | 0 | 9 Uncovered rules attributes.type-system attributes.type-system.non_exhaustive attributes.type-system.non_exhaustive.allowed-positions attributes.type-system.non_exhaustive.construction attributes.type-system.non_exhaustive.external-crate attributes.type-system.non_exhaustive.intro attributes.type-system.non_exhaustive.match attributes.type-system.non_exhaustive.same-crate attributes.type-system.non_exhaustive.syntax | 0.0%
7.7. Debugger | 20 | 0 | 20 Uncovered rules attributes.debugger attributes.debugger.collapse_debuginfo attributes.debugger.collapse_debuginfo.allowed-positions attributes.debugger.collapse_debuginfo.default attributes.debugger.collapse_debuginfo.duplicates attributes.debugger.collapse_debuginfo.intro attributes.debugger.collapse_debuginfo.options attributes.debugger.collapse_debuginfo.syntax attributes.debugger.debugger_visualizer attributes.debugger.debugger_visualizer.allowed-positions attributes.debugger.debugger_visualizer.duplicates attributes.debugger.debugger_visualizer.gdb attributes.debugger.debugger_visualizer.gdb.path attributes.debugger.debugger_visualizer.gdb.pretty attributes.debugger.debugger_visualizer.intro attributes.debugger.debugger_visualizer.natvis attributes.debugger.debugger_visualizer.natvis.intro attributes.debugger.debugger_visualizer.natvis.msvc attributes.debugger.debugger_visualizer.natvis.path attributes.debugger.debugger_visualizer.syntax | 0.0%
8. Statements and expressions | 1 | 0 | 1 Uncovered rules stmt-expr | 0.0%
8.1. Statements | 23 | 0 | 23 Uncovered rules statement statement.attribute statement.decl statement.expr statement.expr.constraint-block statement.expr.intro statement.expr.restriction-semicolon statement.expr.syntax statement.intro statement.item statement.item.associated-scope statement.item.intro statement.item.outer-generics statement.item.scope statement.kind statement.let statement.let.behavior statement.let.constraint statement.let.inference statement.let.intro statement.let.scope statement.let.syntax statement.syntax | 0.0%
8.2. Expressions | 46 | 0 | 46 Uncovered rules expr expr.attr expr.attr.never-before expr.attr.restriction expr.behavior expr.evaluation expr.implicit-borrow expr.implicit-borrow-intro expr.implicit-borrow.application expr.intro expr.move expr.move.copy expr.move.deinitialization expr.move.intro expr.move.movable-place expr.move.place-invalid expr.move.requires-sized expr.mut expr.mut.intro expr.mut.valid-places expr.operand-order expr.operand-order.default expr.operand-order.operands-before-primary expr.operands expr.overload expr.place-value expr.place-value.assignee expr.place-value.intro expr.place-value.parenthesis expr.place-value.place-context expr.place-value.place-expr-kinds expr.place-value.place-memory-location expr.place-value.value-expr-kinds expr.place-value.value-result expr.precedence expr.structure expr.super-macros expr.super-macros.format_args expr.super-macros.format_args.super-operands expr.super-macros.format_args.super-temporaries expr.super-macros.intro expr.super-macros.pin expr.super-macros.pin.super-operands expr.super-macros.pin.super-temporaries expr.syntax expr.temporary | 0.0%
8.2.1. Literal expressions | 87 | 0 | 87 Uncovered rules expr.literal expr.literal.bool expr.literal.bool.intro expr.literal.bool.result expr.literal.byte-char expr.literal.byte-char.escape expr.literal.byte-char.intro expr.literal.byte-char.literal expr.literal.byte-char.literal-content expr.literal.byte-char.no-suffix expr.literal.byte-char.represented expr.literal.byte-char.result expr.literal.byte-char.single expr.literal.byte-string expr.literal.byte-string.escape expr.literal.byte-string.intro expr.literal.byte-string.literal-content expr.literal.byte-string.no-suffix expr.literal.byte-string.raw expr.literal.byte-string.represented expr.literal.byte-string.result expr.literal.byte-string.type expr.literal.c-string expr.literal.c-string.escape expr.literal.c-string.intro expr.literal.c-string.literal-content expr.literal.c-string.no-suffix expr.literal.c-string.raw expr.literal.c-string.represented expr.literal.c-string.result expr.literal.c-string.type expr.literal.char expr.literal.char.escape expr.literal.char.intro expr.literal.char.literal-content expr.literal.char.no-suffix expr.literal.char.represented expr.literal.char.result expr.literal.char.single expr.literal.char.type expr.literal.const-expr expr.literal.continuation expr.literal.escape expr.literal.escape.hex-ascii expr.literal.escape.hex-octet expr.literal.escape.intro expr.literal.escape.sequence expr.literal.escape.simple expr.literal.escape.unicode expr.literal.float expr.literal.float.infer expr.literal.float.inference-default expr.literal.float.inference-error expr.literal.float.inference-unique-type expr.literal.float.intro expr.literal.float.result expr.literal.float.separators-stripped expr.literal.float.suffix expr.literal.float.type-suffix-stripped expr.literal.float.value expr.literal.int expr.literal.int.cast expr.literal.int.infer expr.literal.int.inference-default expr.literal.int.inference-error expr.literal.int.inference-unique-type expr.literal.int.intro expr.literal.int.radix expr.literal.int.radix-prefix-stripped expr.literal.int.representation expr.literal.int.separators-stripped expr.literal.int.suffix expr.literal.int.type-suffix-stripped expr.literal.int.u128-value expr.literal.intro expr.literal.literal-token expr.literal.string expr.literal.string-representation expr.literal.string.escape expr.literal.string.intro expr.literal.string.literal-content expr.literal.string.no-suffix expr.literal.string.raw expr.literal.string.represented expr.literal.string.result expr.literal.string.type expr.literal.syntax | 0.0%
8.2.2. Path expressions | 6 | 0 | 6 Uncovered rules expr.path expr.path.const expr.path.intro expr.path.place expr.path.safety expr.path.syntax | 0.0%
8.2.3. Block expressions | 40 | 0 | 40 Uncovered rules expr.block expr.block.async expr.block.async.anonymous-type expr.block.async.capture expr.block.async.context expr.block.async.edition2018 expr.block.async.function expr.block.async.function.control-flow expr.block.async.function.intro expr.block.async.function.return-try expr.block.async.future expr.block.async.future-result expr.block.async.intro expr.block.async.layout-unspecified expr.block.async.syntax expr.block.attributes expr.block.attributes.inner-attributes expr.block.attributes.valid expr.block.const expr.block.const.context expr.block.const.evaluation expr.block.const.generic-params expr.block.const.intro expr.block.const.not-executed expr.block.const.syntax expr.block.evaluation expr.block.inner-attributes expr.block.intro expr.block.label expr.block.namespace expr.block.null-statement expr.block.result expr.block.sequential-evaluation expr.block.statements expr.block.syntax expr.block.type expr.block.unsafe expr.block.unsafe.intro expr.block.unsafe.syntax expr.block.value | 0.0%
8.2.4. Operator expressions | 108 | 0 | 108 Uncovered rules expr.arith-logic expr.arith-logic.behavior expr.arith-logic.intro expr.arith-logic.syntax expr.as expr.as.bool-char-as-int expr.as.coercions expr.as.enum expr.as.enum.discriminant expr.as.enum.no-drop expr.as.int-as-pointer expr.as.intro expr.as.numeric expr.as.numeric.float-as-int expr.as.numeric.float-narrowing expr.as.numeric.float-widening expr.as.numeric.int-as-float expr.as.numeric.int-extension expr.as.numeric.int-same-size expr.as.numeric.int-truncation expr.as.pointer expr.as.pointer-as-int expr.as.pointer.behavior expr.as.pointer.discard-metadata expr.as.pointer.sized expr.as.pointer.unsized expr.as.result expr.as.syntax expr.as.u8-as-char expr.assign expr.assign.assignee expr.assign.basic expr.assign.behavior expr.assign.behavior-basic expr.assign.behavior-destructuring expr.assign.destructure expr.assign.destructure.assignee expr.assign.destructure.default-binding expr.assign.destructure.discard-value expr.assign.destructure.intro expr.assign.destructure.irrefutable expr.assign.destructure.repeat-ident expr.assign.destructure.tmp-ext expr.assign.destructure.tmp-scopes expr.assign.destructuring-order expr.assign.drop-target expr.assign.evaluation-order expr.assign.intro expr.assign.result expr.assign.syntax expr.bool-logic expr.bool-logic.conditional-evaluation expr.bool-logic.intro expr.bool-logic.syntax expr.borrow.and-and-syntax expr.borrow.raw expr.borrow.raw.intro expr.borrow.raw.invalid-ref expr.borrow.raw.place expr.borrow.raw.result expr.cmp expr.cmp.behavior expr.cmp.intro expr.cmp.paren-chaining expr.cmp.place expr.cmp.syntax expr.cmp.trait expr.compound-assign expr.compound-assign.intro expr.compound-assign.no-value expr.compound-assign.operand-order expr.compound-assign.place expr.compound-assign.primitives expr.compound-assign.result expr.compound-assign.syntax expr.compound-assign.trait expr.deref expr.deref.intro expr.deref.mut expr.deref.result expr.deref.safety expr.deref.syntax expr.deref.traits expr.negate expr.negate.intro expr.negate.results expr.negate.syntax expr.operator expr.operator.borrow expr.operator.borrow.intro expr.operator.borrow.lifetime expr.operator.borrow.mut expr.operator.borrow.result expr.operator.borrow.syntax expr.operator.borrow.temporary expr.operator.int-overflow expr.operator.int-overflow.binary-arith expr.operator.int-overflow.div expr.operator.int-overflow.intro expr.operator.int-overflow.shift expr.operator.int-overflow.unary-neg expr.operator.intro expr.operator.syntax expr.operator.trait expr.try expr.try.intro expr.try.restricted-types expr.try.syntax | 0.0%
8.2.5. Grouped expressions | 6 | 0 | 6 Uncovered rules expr.paren expr.paren.evaluation expr.paren.intro expr.paren.override-precedence expr.paren.place-or-value expr.paren.syntax | 0.0%
8.2.6. Array and index expressions | 22 | 0 | 22 Uncovered rules expr.array expr.array.array expr.array.array-behavior expr.array.array-syntax expr.array.constructor expr.array.index expr.array.index.array expr.array.index.const expr.array.index.syntax expr.array.index.trait expr.array.index.trait-impl expr.array.index.zero-index expr.array.length-operand expr.array.length-restriction expr.array.repeat expr.array.repeat-behavior expr.array.repeat-const-item expr.array.repeat-copy expr.array.repeat-evaluation-zero expr.array.repeat-non-const expr.array.repeat-operand expr.array.syntax | 0.0%
8.2.7. Tuple and index expressions | 16 | 0 | 16 Uncovered rules expr.tuple expr.tuple-index expr.tuple-index.index-name-operand expr.tuple-index.index-syntax expr.tuple-index.intro expr.tuple-index.required-type expr.tuple-index.result expr.tuple-index.syntax expr.tuple.fields expr.tuple.intro expr.tuple.result expr.tuple.syntax expr.tuple.type expr.tuple.unary-tuple-restriction expr.tuple.unit expr.tuple.value | 0.0%
8.2.8. Struct expressions | 14 | 0 | 14 Uncovered rules expr.struct expr.struct.brace-restricted-positions expr.struct.field expr.struct.field.intro expr.struct.field.named expr.struct.field.union-constraint expr.struct.intro expr.struct.syntax expr.struct.tuple-field expr.struct.update expr.struct.update.base-same-type expr.struct.update.fields expr.struct.update.intro expr.struct.update.visibility-constraint | 0.0%
8.2.9. Call expressions | 11 | 0 | 11 Uncovered rules expr.call expr.call.autoref-deref expr.call.convergence expr.call.desugar expr.call.desugar.ambiguity expr.call.desugar.explicit-path expr.call.desugar.fully-qualified expr.call.desugar.limits expr.call.intro expr.call.syntax expr.call.trait | 0.0%
8.2.10. Method call expressions | 12 | 0 | 12 Uncovered rules expr.method expr.method.ambiguous-search expr.method.ambiguous-target expr.method.autoref-deref expr.method.candidate-receivers expr.method.candidate-receivers-refs expr.method.candidate-search expr.method.edition2021 expr.method.intro expr.method.receiver-constraints expr.method.syntax expr.method.target | 0.0%
8.2.11. Field access expressions | 8 | 0 | 8 Uncovered rules expr.field expr.field.autoref-deref expr.field.borrow expr.field.form expr.field.intro expr.field.mut expr.field.not-method-call expr.field.syntax | 0.0%
8.2.12. Closure expressions | 17 | 0 | 17 Uncovered rules expr.closure expr.closure.async expr.closure.async.edition2018 expr.closure.async.future expr.closure.async.intro expr.closure.capture-inference expr.closure.capture-move expr.closure.capture-mut-ref expr.closure.captures expr.closure.explicit-type-body expr.closure.intro expr.closure.param-attributes expr.closure.param-type expr.closure.parameter-restriction expr.closure.syntax expr.closure.trait-impl expr.closure.unique-type | 0.0%
8.2.13. Loop expressions | 56 | 0 | 56 Uncovered rules expr.loop expr.loop.block-labels expr.loop.block-labels.break expr.loop.block-labels.intro expr.loop.block-labels.label-required expr.loop.block-labels.syntax expr.loop.break expr.loop.break-label expr.loop.break-value expr.loop.break-value.intro expr.loop.break-value.loop expr.loop.break.intro expr.loop.break.label expr.loop.break.syntax expr.loop.break.value expr.loop.continue expr.loop.continue-label expr.loop.continue.for expr.loop.continue.in-loop-only expr.loop.continue.intro expr.loop.continue.label expr.loop.continue.syntax expr.loop.continue.while expr.loop.explicit-result expr.loop.for expr.loop.for.condition expr.loop.for.desugar expr.loop.for.intro expr.loop.for.lang-items expr.loop.for.syntax expr.loop.infinite expr.loop.infinite.break expr.loop.infinite.diverging expr.loop.infinite.intro expr.loop.infinite.syntax expr.loop.intro expr.loop.label expr.loop.label.control-flow expr.loop.label.intro expr.loop.label.ref expr.loop.label.syntax expr.loop.syntax expr.loop.while expr.loop.while.chains expr.loop.while.chains.intro expr.loop.while.condition expr.loop.while.eval expr.loop.while.exit expr.loop.while.grammar expr.loop.while.intro expr.loop.while.let expr.loop.while.let.desugar expr.loop.while.let.intro expr.loop.while.let.or-pattern expr.loop.while.repeat expr.loop.while.syntax | 0.0%
8.2.14. Range expressions | 5 | 0 | 5 Uncovered rules expr.range expr.range.behavior expr.range.equivalence expr.range.for expr.range.syntax | 0.0%
8.2.15. If expressions | 18 | 0 | 18 Uncovered rules expr.if expr.if.chains expr.if.chains.bindings expr.if.chains.intro expr.if.chains.or expr.if.chains.order expr.if.condition expr.if.condition-true expr.if.edition2024 expr.if.else expr.if.else-if expr.if.intro expr.if.let expr.if.let.intro expr.if.let.or-pattern expr.if.result expr.if.syntax expr.if.type | 0.0%
8.2.16. Match expressions | 25 | 0 | 25 Uncovered rules expr.match expr.match.attributes expr.match.attributes.inner expr.match.attributes.outer expr.match.binding-restriction expr.match.guard expr.match.guard.behavior expr.match.guard.bound-variables expr.match.guard.intro expr.match.guard.next expr.match.guard.no-mutation expr.match.guard.shared-ref expr.match.guard.type expr.match.guard.value expr.match.intro expr.match.or-pattern expr.match.or-patterns-restriction expr.match.pattern-var-binding expr.match.pattern-vars expr.match.scrutinee expr.match.scrutinee-behavior expr.match.scrutinee-constraint expr.match.scrutinee-place expr.match.scrutinee-value expr.match.syntax | 0.0%
8.2.17. Return expressions | 4 | 0 | 4 Uncovered rules expr.return expr.return.behavior expr.return.intro expr.return.syntax | 0.0%
8.2.18. Await expressions | 9 | 0 | 9 Uncovered rules expr.await expr.await.allowed-positions expr.await.construct expr.await.desugar expr.await.edition2018 expr.await.effects expr.await.intro expr.await.syntax expr.await.task | 0.0%
8.2.19. Underscore expressions | 5 | 0 | 5 Uncovered rules expr.placeholder expr.placeholder.intro expr.placeholder.lhs-assignment-only expr.placeholder.pattern expr.placeholder.syntax | 0.0%
9. Patterns | 140 | 0 | 140 Uncovered rules patterns patterns.behavior patterns.behavior.nested-or-patterns patterns.const patterns.const.aggregate patterns.const.builtin-aggregate patterns.const.exhaustive patterns.const.float patterns.const.generic patterns.const.immutable patterns.const.partial-eq patterns.const.pointer patterns.const.primitive patterns.const.ref patterns.const.structural-equality patterns.const.translation patterns.constraints patterns.constraints.exhaustiveness-or-pattern patterns.constraints.match-type-check patterns.constraints.pattern patterns.destructure patterns.destructure.intro patterns.destructure.named-field-shorthand patterns.destructure.wildcard patterns.for patterns.ident patterns.ident.bare patterns.ident.binding patterns.ident.binding.auto-deref patterns.ident.binding.default-mode patterns.ident.binding.intro patterns.ident.binding.mixed patterns.ident.binding.mode-limitations-binding patterns.ident.binding.mode-limitations-reference patterns.ident.binding.mode-limitations-reference.edition2024 patterns.ident.binding.mode-limitations.edition2024 patterns.ident.binding.move patterns.ident.binding.nested-references patterns.ident.binding.non-reference patterns.ident.binding.ref patterns.ident.binding.ref-mut patterns.ident.binding.top-down patterns.ident.constraint patterns.ident.intro patterns.ident.move patterns.ident.precedent patterns.ident.ref patterns.ident.ref-ignored patterns.ident.refutable patterns.ident.scope patterns.ident.scrutinized patterns.ident.syntax patterns.ident.unique patterns.if-let patterns.intro patterns.let patterns.literal patterns.literal.intro patterns.literal.refutable patterns.literal.syntax patterns.match patterns.or patterns.param patterns.paren patterns.paren.intro patterns.paren.syntax patterns.path patterns.path.intro patterns.path.qualified patterns.path.refutable patterns.path.syntax patterns.path.unqualified patterns.precedence patterns.range patterns.range.bound patterns.range.constraint-bound-path patterns.range.constraint-nonempty patterns.range.constraint-slice patterns.range.edition2021 patterns.range.exclusive patterns.range.float-restriction patterns.range.from patterns.range.inclusive patterns.range.intro patterns.range.literal-value patterns.range.negation patterns.range.path-value patterns.range.refutable patterns.range.refutable-char patterns.range.refutable-integer patterns.range.syntax patterns.range.to-exclusive patterns.range.to-inclusive patterns.range.type patterns.ref patterns.ref.intro patterns.ref.mut patterns.ref.ref-ref patterns.ref.refutable patterns.ref.syntax patterns.refutable patterns.rest patterns.rest.allowed-patterns patterns.rest.intro patterns.rest.refutable patterns.rest.syntax patterns.slice patterns.slice.intro patterns.slice.refutable-array patterns.slice.refutable-slice patterns.slice.restriction patterns.slice.syntax patterns.struct patterns.struct.binding-shorthand patterns.struct.constraint-struct patterns.struct.constraint-union patterns.struct.ignore-rest patterns.struct.intro patterns.struct.namespace patterns.struct.refutable patterns.struct.syntax patterns.syntax patterns.tuple patterns.tuple-struct patterns.tuple-struct.intro patterns.tuple-struct.namespace patterns.tuple-struct.refutable patterns.tuple-struct.syntax patterns.tuple.intro patterns.tuple.refutable patterns.tuple.rest-syntax patterns.tuple.syntax patterns.usage patterns.while-let patterns.wildcard patterns.wildcard.intro patterns.wildcard.no-binding patterns.wildcard.refutable patterns.wildcard.struct-matcher patterns.wildcard.syntax | 0.0%
10. Type system | 0 |  |  |
10.1. Types | 22 | 0 | 22 Uncovered rules type type.builtin type.intro type.kinds type.name type.name.grouped type.name.inference type.name.intro type.name.macro-expansion type.name.never type.name.parenthesized type.name.parenthesized.intro type.name.parenthesized.syntax type.name.path type.name.pointer type.name.sequence type.name.syntax type.name.trait type.recursive type.recursive.constraint type.recursive.intro type.user-defined | 0.0%
10.1.1. Boolean type | 23 | 0 | 23 Uncovered rules type.bool type.bool.expr type.bool.expr.and type.bool.expr.cmp type.bool.expr.cmp.eq type.bool.expr.cmp.greater type.bool.expr.cmp.greater-eq type.bool.expr.cmp.less type.bool.expr.cmp.less-eq type.bool.expr.cmp.not-eq type.bool.expr.not type.bool.expr.or type.bool.expr.xor type.bool.intro type.bool.layout type.bool.literal type.bool.namespace type.bool.repr type.bool.traits type.bool.usage type.bool.usage-condition type.bool.usage-lazy-operator type.bool.validity | 0.0%
10.1.2. Numeric types | 10 | 0 | 10 Uncovered rules type.numeric type.numeric.float type.numeric.int type.numeric.int.signed type.numeric.int.size type.numeric.int.size.isize type.numeric.int.size.minimum type.numeric.int.size.usize type.numeric.int.unsigned type.numeric.validity | 0.0%
10.1.3. Textual types | 9 | 0 | 9 Uncovered rules type.layout.char-layout type.layout.char-validity type.text type.text.char-precondition type.text.char-value type.text.intro type.text.layout type.text.str-unsized type.text.str-value | 0.0%
10.1.4. Never type | 5 | 0 | 5 Uncovered rules type.never type.never.coercion type.never.constraint type.never.intro type.never.syntax | 0.0%
10.1.5. Tuple types | 9 | 0 | 9 Uncovered rules type.tuple type.tuple.access type.tuple.constructor type.tuple.field-name type.tuple.field-number type.tuple.intro type.tuple.restriction type.tuple.syntax type.tuple.unit | 0.0%
10.1.6. Array types | 5 | 0 | 5 Uncovered rules type.array type.array.constraint type.array.index type.array.intro type.array.syntax | 0.0%
10.1.7. Slice types | 5 | 0 | 5 Uncovered rules type.slice type.slice.intro type.slice.safe type.slice.syntax type.slice.unsized | 0.0%
10.1.8. Struct types | 7 | 0 | 7 Uncovered rules type.struct type.struct.constructor type.struct.field-visibility type.struct.intro type.struct.layout type.struct.tuple type.struct.unit | 0.0%
10.1.9. Enumerated types | 6 | 0 | 6 Uncovered rules type.enum type.enum.constructor type.enum.declaration type.enum.intro type.enum.name type.enum.value | 0.0%
10.1.10. Union types | 6 | 0 | 6 Uncovered rules type.union type.union.access type.union.constraint type.union.intro type.union.layout type.union.safety | 0.0%
10.1.11. Function item types | 6 | 0 | 6 Uncovered rules type.fn-item type.fn-item.coercion type.fn-item.intro type.fn-item.name type.fn-item.traits type.fn-item.unique | 0.0%
10.1.12. Closure types | 55 | 0 | 55 Uncovered rules type.closure type.closure.async.input type.closure.async.traits type.closure.async.traits.async-family type.closure.async.traits.fn-family type.closure.call type.closure.call.fn type.closure.call.fn-mut type.closure.call.intro type.closure.capture type.closure.capture.copy type.closure.capture.intro type.closure.capture.precedence type.closure.capture.precision.box-deref type.closure.capture.precision.box-move.read type.closure.capture.precision.box-non-move.moved type.closure.capture.precision.box-non-move.not-moved type.closure.capture.precision.capture-path type.closure.capture.precision.dereference-shared type.closure.capture.precision.discriminants type.closure.capture.precision.discriminants.multiple-variant type.closure.capture.precision.discriminants.non_exhaustive type.closure.capture.precision.discriminants.reads type.closure.capture.precision.discriminants.single-variant type.closure.capture.precision.discriminants.uninhabited-variants type.closure.capture.precision.edition2018.composite type.closure.capture.precision.edition2018.drop-order type.closure.capture.precision.edition2018.entirety type.closure.capture.precision.edition2018.move type.closure.capture.precision.edition2018.wildcard type.closure.capture.precision.intro type.closure.capture.precision.move-dereference type.closure.capture.precision.place-projection type.closure.capture.precision.range-patterns type.closure.capture.precision.range-patterns.reads type.closure.capture.precision.raw-pointer-dereference type.closure.capture.precision.shared-prefix type.closure.capture.precision.slice-patterns type.closure.capture.precision.slice-patterns.arrays type.closure.capture.precision.slice-patterns.slices type.closure.capture.precision.unaligned type.closure.capture.precision.union type.closure.capture.precision.wildcard type.closure.capture.precision.wildcard.array-slice type.closure.capture.precision.wildcard.destructuring type.closure.capture.precision.wildcard.fields type.closure.capture.precision.wildcard.initialized type.closure.capture.precision.wildcard.reads type.closure.drop-order type.closure.intro type.closure.non-capturing type.closure.traits type.closure.traits.behavior type.closure.traits.intro type.closure.unique-immutable | 0.0%
10.1.13. Pointer types | 22 | 0 | 22 Uncovered rules type.pointer type.pointer.intro type.pointer.raw type.pointer.raw.cmp type.pointer.raw.constructor type.pointer.raw.copy type.pointer.raw.intro type.pointer.raw.safety type.pointer.raw.syntax type.pointer.reference type.pointer.reference.mut type.pointer.reference.mut.copy type.pointer.reference.mut.intro type.pointer.reference.shared type.pointer.reference.shared.constraint-mutation type.pointer.reference.shared.copy type.pointer.reference.shared.intro type.pointer.reference.syntax type.pointer.smart type.pointer.validity type.pointer.validity.pointer-fragment type.pointer.validity.raw | 0.0%
10.1.14. Function pointer types | 7 | 0 | 7 Uncovered rules type.fn-pointer type.fn-pointer.attributes type.fn-pointer.coercion type.fn-pointer.constraint-variadic type.fn-pointer.intro type.fn-pointer.qualifiers type.fn-pointer.syntax | 0.0%
10.1.15. Trait object types | 11 | 0 | 11 Uncovered rules type.trait-object type.trait-object.alias type.trait-object.constraint type.trait-object.impls type.trait-object.intro type.trait-object.lifetime-bounds type.trait-object.name type.trait-object.syntax type.trait-object.syntax-edition2018 type.trait-object.syntax-edition2021 type.trait-object.unsized | 0.0%
10.1.16. Impl trait type | 23 | 0 | 23 Uncovered rules type.impl-trait type.impl-trait.constraint type.impl-trait.generic-capture.auto type.impl-trait.generic-capture.auto.intro type.impl-trait.generic-capture.edition2024 type.impl-trait.generic-capture.precise type.impl-trait.generic-capture.precise.constraint-in-trait type.impl-trait.generic-capture.precise.constraint-lifetime type.impl-trait.generic-capture.precise.constraint-param-impl-trait type.impl-trait.generic-capture.precise.constraint-single type.impl-trait.generic-capture.precise.use type.impl-trait.generic-captures type.impl-trait.intro type.impl-trait.param type.impl-trait.param.generic type.impl-trait.param.intro type.impl-trait.return type.impl-trait.return-in-trait type.impl-trait.return-in-trait.desugaring type.impl-trait.return-in-trait.intro type.impl-trait.return.constraint-body type.impl-trait.return.intro type.impl-trait.syntax | 0.0%
10.1.17. Type parameters | 1 | 0 | 1 Uncovered rules type.generic | 0.0%
10.1.18. Inferred type | 4 | 0 | 4 Uncovered rules type.inferred type.inferred.constraint type.inferred.intro type.inferred.syntax | 0.0%
10.2. Dynamically sized types | 7 | 0 | 7 Uncovered rules dynamic-sized dynamic-sized.intro dynamic-sized.pointer-types dynamic-sized.question-sized dynamic-sized.restriction dynamic-sized.struct-field dynamic-sized.trait-impl | 0.0%
10.3. Type layout | 68 | 0 | 68 Uncovered rules layout layout.array layout.closure layout.guarantees layout.intro layout.pointer layout.pointer.intro layout.pointer.thin layout.pointer.unsized layout.primitive layout.primitive.align layout.primitive.size layout.primitive.size-int layout.properties layout.properties.align layout.properties.size layout.properties.sized layout.repr layout.repr.align-packed layout.repr.alignment layout.repr.alignment.align layout.repr.alignment.constraint-alignment layout.repr.alignment.constraint-exclusive layout.repr.alignment.enum layout.repr.alignment.intro layout.repr.alignment.packed layout.repr.alignment.packed-fields layout.repr.alignment.packed-padding layout.repr.attribute layout.repr.c layout.repr.c.adt layout.repr.c.adt.fields layout.repr.c.adt.intro layout.repr.c.adt.tag layout.repr.c.constraint layout.repr.c.enum layout.repr.c.intro layout.repr.c.struct layout.repr.c.struct.align layout.repr.c.struct.size-field-offset layout.repr.c.union layout.repr.c.union.intro layout.repr.c.union.size-align layout.repr.inter-field layout.repr.intro layout.repr.kinds layout.repr.primitive layout.repr.primitive-c layout.repr.primitive.adt layout.repr.primitive.constraint layout.repr.primitive.enum layout.repr.primitive.intro layout.repr.rust layout.repr.rust.alignment layout.repr.rust.field-storage layout.repr.rust.intro layout.repr.rust.layout layout.repr.rust.unspecified layout.repr.transparent layout.repr.transparent.constraint-exclusive layout.repr.transparent.constraint-field layout.repr.transparent.layout-abi layout.slice layout.str layout.trait-object layout.tuple layout.tuple.general layout.tuple.unit | 0.0%
10.4. Interior mutability | 9 | 0 | 9 Uncovered rules interior-mut interior-mut.abstraction interior-mut.atomic interior-mut.intro interior-mut.mut-unsafe-cell interior-mut.no-constraint interior-mut.ref-cell interior-mut.shared-ref interior-mut.unsafe-cell | 0.0%
10.5. Subtyping and variance | 12 | 0 | 12 Uncovered rules subtype subtype.higher-ranked subtype.intro subtype.kinds subtyping.variance subtyping.variance.builtin-composite-types subtyping.variance.builtin-types subtyping.variance.contravariant subtyping.variance.covariant subtyping.variance.intro subtyping.variance.invariant subtyping.variance.user-composite-types | 0.0%
10.6. Trait and lifetime bounds | 22 | 0 | 22 Uncovered rules bound bound.higher-ranked bound.higher-ranked.intro bound.higher-ranked.syntax bound.higher-ranked.trait bound.implied bound.implied.context bound.implied.def bound.implied.intro bound.implied.trait bound.intro bound.lifetime bound.lifetime.intro bound.lifetime.outlive-lifetime bound.lifetime.outlive-type bound.satisfaction bound.sized bound.special bound.syntax bound.trait-object bound.trivial bound.use | 0.0%
10.7. Type coercions | 45 | 0 | 45 Uncovered rules coerce coerce.as coerce.intro coerce.least-upper-bound coerce.least-upper-bound.computation coerce.least-upper-bound.computation-identity coerce.least-upper-bound.computation-replace coerce.least-upper-bound.computation-unify coerce.least-upper-bound.intro coerce.least-upper-bound.target coerce.site coerce.site.argument coerce.site.array coerce.site.block coerce.site.constructor coerce.site.intro coerce.site.let coerce.site.parenthesis coerce.site.repeat coerce.site.return coerce.site.subexpr coerce.site.tuple coerce.site.value coerce.types coerce.types.closure coerce.types.deref coerce.types.deref-mut coerce.types.fn coerce.types.intro coerce.types.mut-pointer coerce.types.mut-reborrow coerce.types.mut-to-pointer coerce.types.never coerce.types.ref-to-pointer coerce.types.reflexive coerce.types.transitive coerce.types.unsize coerce.unsize coerce.unsize.intro coerce.unsize.slice coerce.unsize.trait coerce.unsize.trait-object coerce.unsize.trait-upcast coerce.unsized.composite coerce.unsized.pointer | 0.0%
10.8. Destructors | 49 | 1 | 48 Uncovered rules destructors destructors.drop_in_place destructors.forget destructors.intro destructors.manually-suppressing destructors.operation destructors.process-termination destructors.scope destructors.scope.bindings destructors.scope.bindings.intro destructors.scope.bindings.or-patterns destructors.scope.bindings.patterns destructors.scope.block destructors.scope.const-promotion destructors.scope.desugaring destructors.scope.expression destructors.scope.function destructors.scope.intro destructors.scope.lifetime-extension destructors.scope.lifetime-extension.exprs.borrows destructors.scope.lifetime-extension.exprs.extending destructors.scope.lifetime-extension.exprs.super-macros destructors.scope.lifetime-extension.let destructors.scope.lifetime-extension.patterns destructors.scope.lifetime-extension.patterns.extending destructors.scope.lifetime-extension.patterns.let destructors.scope.lifetime-extension.static destructors.scope.lifetime-extension.sub-expressions destructors.scope.list destructors.scope.match-arm destructors.scope.nesting destructors.scope.nesting.expr-statement destructors.scope.nesting.function destructors.scope.nesting.function-body destructors.scope.nesting.let-initializer destructors.scope.nesting.match destructors.scope.nesting.match-arm destructors.scope.nesting.match-guard destructors.scope.nesting.other destructors.scope.nesting.statement destructors.scope.operands destructors.scope.operators destructors.scope.params destructors.scope.statement destructors.scope.temporary destructors.scope.temporary.edition2024 destructors.scope.temporary.enclosing destructors.scope.temporary.intro | 2.1%
10.9. Lifetime elision | 24 | 0 | 24 Uncovered rules lifetime-elision lifetime-elision.const-static lifetime-elision.const-static.fn-references lifetime-elision.const-static.implicit-static lifetime-elision.function lifetime-elision.function.explicit-placeholder lifetime-elision.function.implicit-lifetime-parameters lifetime-elision.function.intro lifetime-elision.function.lifetimes-not-inferred lifetime-elision.function.only-functions lifetime-elision.function.output-lifetime lifetime-elision.function.receiver-lifetime lifetime-elision.trait-object lifetime-elision.trait-object.containing-type lifetime-elision.trait-object.containing-type-explicit lifetime-elision.trait-object.containing-type-unique lifetime-elision.trait-object.default lifetime-elision.trait-object.explicit-bound lifetime-elision.trait-object.explicit-placeholder lifetime-elision.trait-object.innermost-type lifetime-elision.trait-object.intro lifetime-elision.trait-object.static-lifetime lifetime-elision.trait-object.trait-bounds lifetime-elision.trait-object.trait-unique | 0.0%
11. Special types and traits | 54 | 0 | 54 Uncovered rules lang-types lang-types.arc lang-types.arc.receiver lang-types.auto-traits lang-types.auto-traits.aggregate lang-types.auto-traits.auto-impl lang-types.auto-traits.builtin-composite lang-types.auto-traits.closure lang-types.auto-traits.fn-item-pointer lang-types.auto-traits.generic-impl lang-types.auto-traits.negative lang-types.auto-traits.trait-object-marker lang-types.box lang-types.box.deref lang-types.box.fundamental lang-types.box.intro lang-types.box.receiver lang-types.clone lang-types.clone.builtin-copy lang-types.clone.builtin-types lang-types.clone.closure lang-types.clone.intro lang-types.clone.tuple lang-types.copy lang-types.copy.behavior lang-types.copy.builtin-types lang-types.copy.closure lang-types.copy.constraint lang-types.copy.fn-item lang-types.copy.fn-pointer lang-types.copy.intro lang-types.copy.tuple lang-types.deref lang-types.drop lang-types.intro lang-types.ops lang-types.phantom-data lang-types.pin lang-types.pin.receiver lang-types.rc lang-types.rc.receiver lang-types.send lang-types.sized lang-types.sized.implicit-impl lang-types.sized.implicit-sized lang-types.sized.intro lang-types.sized.relaxation lang-types.sync lang-types.sync.intro lang-types.sync.static-constraint lang-types.termination lang-types.unsafe-cell lang-types.unsafe-cell.interior-mut lang-types.unsafe-cell.read-only-alloc | 0.0%
12. Names | 24 | 0 | 24 Uncovered rules names names.explicit names.explicit.binding names.explicit.expr names.explicit.generics names.explicit.higher-ranked-bounds names.explicit.item-decl names.explicit.list names.explicit.macro-invocation names.explicit.macro_export names.explicit.macro_use names.implicit names.implicit.builtin-attributes names.implicit.derive-helpers names.implicit.extern-prelude names.implicit.lifetime-static names.implicit.lints names.implicit.list names.implicit.prelude names.implicit.primitive-types names.implicit.root names.implicit.stdlib names.implicit.tool-attributes names.intro | 0.0%
12.1. Namespaces | 8 | 0 | 8 Uncovered rules names.namespaces names.namespaces.intro names.namespaces.kinds names.namespaces.sub-namespaces names.namespaces.sub-namespaces.intro names.namespaces.without names.namespaces.without.fields names.namespaces.without.use | 0.0%
12.2. Scopes | 46 | 0 | 46 Uncovered rules names.scopes names.scopes.associated-items names.scopes.associated-items.duplicate names.scopes.associated-items.scope names.scopes.derive names.scopes.derive.scope names.scopes.derive.shadow names.scopes.generic-parameters names.scopes.generic-parameters.bounds names.scopes.generic-parameters.inner-items names.scopes.generic-parameters.order-independent names.scopes.generic-parameters.param-list names.scopes.generic-parameters.shadow names.scopes.intro names.scopes.items names.scopes.items.duplicate names.scopes.items.module names.scopes.items.nested-modules names.scopes.items.shadow-prelude names.scopes.items.statement names.scopes.lifetimes names.scopes.lifetimes.generic names.scopes.lifetimes.higher-ranked names.scopes.lifetimes.impl-trait names.scopes.lifetimes.special names.scopes.loop-label names.scopes.loop-label.scope names.scopes.loop-label.shadow names.scopes.macro_rules names.scopes.pattern-bindings names.scopes.pattern-bindings.closure names.scopes.pattern-bindings.items names.scopes.pattern-bindings.let names.scopes.pattern-bindings.let-chains names.scopes.pattern-bindings.loop names.scopes.pattern-bindings.match-arm names.scopes.pattern-bindings.parameter names.scopes.pattern-bindings.shadow names.scopes.prelude names.scopes.prelude.intro names.scopes.prelude.layers names.scopes.prelude.shadow names.scopes.self names.scopes.self.def-scope names.scopes.self.impl-scope names.scopes.self.intro | 0.0%
12.3. Preludes | 34 | 0 | 34 Uncovered rules names.preludes names.preludes.extern names.preludes.extern.core names.preludes.extern.edition2018 names.preludes.extern.intro names.preludes.extern.no_std names.preludes.extern.no_std.allowed-positions names.preludes.extern.no_std.duplicates names.preludes.extern.no_std.edition2018 names.preludes.extern.no_std.intro names.preludes.extern.no_std.macro_use names.preludes.extern.no_std.module names.preludes.extern.no_std.syntax names.preludes.extern.std names.preludes.intro names.preludes.kinds names.preludes.lang names.preludes.lang.entities names.preludes.lang.intro names.preludes.macro_use names.preludes.macro_use.intro names.preludes.no_implicit_prelude names.preludes.no_implicit_prelude.allowed-positions names.preludes.no_implicit_prelude.duplicates names.preludes.no_implicit_prelude.edition2018 names.preludes.no_implicit_prelude.excluded-preludes names.preludes.no_implicit_prelude.intro names.preludes.no_implicit_prelude.lang names.preludes.no_implicit_prelude.syntax names.preludes.std names.preludes.std.intro names.preludes.std.module names.preludes.tool names.preludes.tool.intro | 0.0%
12.4. Paths | 54 | 0 | 54 Uncovered rules paths paths.canonical paths.canonical.alias paths.canonical.bare-impl-prefix paths.canonical.def paths.canonical.intro paths.canonical.local-canonical-path paths.canonical.module-prefix paths.canonical.non-canonical paths.canonical.trait-impl-prefix paths.expr paths.expr.argument-order paths.expr.complex-const-params paths.expr.impl-trait-params paths.expr.intro paths.expr.syntax paths.expr.turbofish paths.intro paths.qualified paths.qualified.intro paths.qualified.syntax paths.qualifiers paths.qualifiers.crate paths.qualifiers.crate.allowed-positions paths.qualifiers.crate.intro paths.qualifiers.global-root paths.qualifiers.global-root.edition2018 paths.qualifiers.global-root.intro paths.qualifiers.macro-crate paths.qualifiers.macro-crate.allowed-positions paths.qualifiers.macro-crate.hygiene paths.qualifiers.mod-self paths.qualifiers.mod-self.intro paths.qualifiers.mod-self.restriction paths.qualifiers.self-pat paths.qualifiers.super paths.qualifiers.super.allowed-positions paths.qualifiers.super.intro paths.qualifiers.super.repetition paths.qualifiers.type-self paths.qualifiers.type-self.allowed-positions paths.qualifiers.type-self.impl paths.qualifiers.type-self.intro paths.qualifiers.type-self.no-generics paths.qualifiers.type-self.scope paths.qualifiers.type-self.trait paths.qualifiers.type-self.type paths.simple paths.simple.intro paths.simple.syntax paths.type paths.type.intro paths.type.syntax paths.type.turbofish | 0.0%
12.5. Name resolution | 29 | 0 | 29 Uncovered rules names.resolution names.resolution.expansion names.resolution.expansion.expansion-order-stability names.resolution.expansion.imports names.resolution.expansion.imports.ambiguity names.resolution.expansion.imports.ambiguity.glob-vs-glob names.resolution.expansion.imports.ambiguity.glob-vs-outer names.resolution.expansion.imports.ambiguity.intro names.resolution.expansion.imports.ambiguity.path-vs-textual-macro names.resolution.expansion.imports.intro names.resolution.expansion.imports.shadowing names.resolution.expansion.imports.shadowing.shared-scope names.resolution.expansion.intro names.resolution.expansion.macros names.resolution.expansion.macros.ambiguity names.resolution.expansion.macros.ambiguity.built-in-attr names.resolution.expansion.macros.ambiguity.more-expanded-vs-outer names.resolution.expansion.macros.intro names.resolution.expansion.macros.reserved-names names.resolution.expansion.macros.visitation-order names.resolution.expansion.speculation names.resolution.expansion.unresolved-invocations names.resolution.general names.resolution.general.intro names.resolution.general.scopes names.resolution.general.scopes.intro names.resolution.intro names.resolution.primary names.resolution.type-relative | 0.0%
12.6. Visibility and privacy | 18 | 0 | 18 Uncovered rules vis vis.access vis.default vis.intro vis.name-hierarchy vis.privacy vis.reexports vis.reexports.intro vis.reexports.private-item vis.scoped vis.scoped.crate vis.scoped.edition2018 vis.scoped.in vis.scoped.intro vis.scoped.self vis.scoped.super vis.syntax vis.usage | 0.0%
13. Memory model | 6 | 0 | 6 Uncovered rules memory memory.bytes memory.bytes.contents memory.bytes.init memory.bytes.intro memory.bytes.uninit | 0.0%
13.1. Memory allocation and lifetime | 3 | 0 | 3 Uncovered rules alloc alloc.dynamic alloc.static | 0.0%
13.2. Variables | 6 | 0 | 6 Uncovered rules variable variable.init variable.intro variable.local variable.local-mut variable.param-mut | 0.0%
14. Panic | 21 | 0 | 21 Uncovered rules panic panic.control panic.intro panic.lang-ops panic.panic_handler panic.panic_handler.allowed-positions panic.panic_handler.intro panic.panic_handler.std panic.panic_handler.std.kinds panic.panic_handler.std.no_std panic.panic_handler.unique panic.strategy panic.strategy.intro panic.unwind panic.unwind.destruction panic.unwind.ffi panic.unwind.ffi.catch-foreign panic.unwind.ffi.dispose-panic panic.unwind.ffi.intro panic.unwind.ffi.undefined panic.unwind.intro | 0.0%
15. Linkage | 27 | 0 | 27 Uncovered rules link link.bin link.cdylib link.crt link.crt.crt-static link.crt.ineffective link.crt.intro link.crt.target_feature link.dependency link.dependency-dynamic link.dependency-prefer-dynamic link.dependency-rlib link.dependency-staticlib link.dylib link.foreign-code link.foreign-code.foreign-linkers link.intro link.lib link.proc-macro link.repetition link.rlib link.staticlib link.type link.unwinding link.unwinding.intro link.unwinding.potential link.unwinding.prohibited | 0.0%
16. Inline assembly | 120 | 1 | 119 Uncovered rules asm asm.abi-clobbers asm.abi-clobbers.explicit-have-precedence asm.abi-clobbers.intro asm.abi-clobbers.many asm.abi-clobbers.must-specify asm.abi-clobbers.supported-abis asm.attributes asm.attributes.starts-with-template asm.attributes.supported-attributes asm.directives asm.directives.stateful asm.directives.subset-supported asm.directives.supported-directives asm.example asm.intro asm.naked-rules asm.naked-rules.black-box asm.naked-rules.callee-saved-registers asm.naked-rules.caller-saved-registers asm.naked-rules.intro asm.naked-rules.mem-same-as-ffi asm.naked-rules.noreturn asm.naked-rules.reg-not-input asm.naked-rules.unwind asm.operand-type asm.operand-type.global_asm-restriction asm.operand-type.left-to-right asm.operand-type.naked_asm-restriction asm.operand-type.supported-operands asm.operand-type.supported-operands.const asm.operand-type.supported-operands.in asm.operand-type.supported-operands.inlateout asm.operand-type.supported-operands.inout asm.operand-type.supported-operands.inout-arrow asm.operand-type.supported-operands.lateout asm.operand-type.supported-operands.out asm.operand-type.supported-operands.sym asm.options asm.options.checks asm.options.checks.label-with-outputs asm.options.checks.mutually-exclusive asm.options.checks.noreturn asm.options.checks.pure asm.options.global_asm-restriction asm.options.naked_asm-restriction asm.options.supported-options asm.options.supported-options.att_syntax asm.options.supported-options.nomem asm.options.supported-options.noreturn asm.options.supported-options.nostack asm.options.supported-options.preserves_flags asm.options.supported-options.pure asm.options.supported-options.raw asm.options.supported-options.readonly asm.register-names asm.register-names.fp-bp-reserved asm.register-names.not-for-io asm.register-names.supported-register-aliases asm.register-operands asm.register-operands.allowed-types asm.register-operands.equivalence-to-base-register asm.register-operands.error-overlapping asm.register-operands.error-two-operands asm.register-operands.register-or-class asm.register-operands.separate-input-output asm.register-operands.smaller-value asm.register-operands.supported-register-classes asm.register-operands.value-type-constraints asm.rules asm.rules.arm64ec asm.rules.black-box asm.rules.intro asm.rules.mem-same-as-ffi asm.rules.noreturn asm.rules.not-exactly-once asm.rules.not-successive asm.rules.only-on-exit asm.rules.preserved-registers asm.rules.preserves_flags asm.rules.pure asm.rules.reg-not-input asm.rules.reg-not-output asm.rules.stack-below-sp asm.rules.unwind asm.rules.x86-df asm.rules.x86-prefix-restriction asm.rules.x86-x87 asm.scope asm.scope.asm asm.scope.global_asm asm.scope.intro asm.scope.naked_asm asm.stable-targets asm.syntax asm.target-specific-directives asm.target-specific-directives.arm-32-bit asm.target-specific-directives.dwarf-unwinding asm.target-specific-directives.structured-exception-handling asm.target-specific-directives.x86 asm.template-modifiers asm.template-modifiers.intro asm.template-modifiers.only-one asm.template-modifiers.smaller-value asm.template-modifiers.supported-modifiers asm.ts-args asm.ts-args.at-least-once asm.ts-args.before-other-args asm.ts-args.llvm-syntax asm.ts-args.no-implicit asm.ts-args.one-or-more asm.ts-args.opaque asm.ts-args.order asm.ts-args.positional-first asm.ts-args.register-operands asm.ts-args.syntax asm.validity asm.validity.necessary-but-not-sufficient asm.validity.non-exhaustive | 0.9%
17. Unsafety | 11 | 0 | 11 Uncovered rules safety safety.intro safety.unsafe-attribute safety.unsafe-call safety.unsafe-deref safety.unsafe-extern safety.unsafe-impl safety.unsafe-ops safety.unsafe-static safety.unsafe-target-feature-call safety.unsafe-union-access | 0.0%
17.1. The unsafe keyword | 16 | 0 | 16 Uncovered rules unsafe unsafe.attribute unsafe.block unsafe.block.fn-body unsafe.block.intro unsafe.extern unsafe.extern.edition2024 unsafe.fn unsafe.fn.intro unsafe.fn.safety unsafe.impl unsafe.intro unsafe.positions unsafe.trait unsafe.trait.intro unsafe.trait.safety | 0.0%
17.2. Behavior considered undefined | 42 | 0 | 42 Uncovered rules undefined undefined.alias undefined.asm undefined.call undefined.dangling undefined.dangling.alloc-limit undefined.dangling.dynamic-size undefined.dangling.general undefined.dangling.zero-size undefined.general undefined.immutable undefined.intrinsic undefined.invalid undefined.misaligned undefined.misaligned.general undefined.misaligned.load-store undefined.misaligned.packed undefined.misaligned.raw undefined.misaligned.reference undefined.place-projection undefined.pointed-to undefined.pointer-access undefined.race undefined.runtime undefined.soundness undefined.target-feature undefined.validity undefined.validity.bool undefined.validity.char undefined.validity.const-provenance undefined.validity.enum undefined.validity.fn-pointer undefined.validity.general undefined.validity.never undefined.validity.reference-box undefined.validity.scalar undefined.validity.str undefined.validity.struct undefined.validity.undef undefined.validity.union undefined.validity.valid-range undefined.validity.wide | 0.0%
17.3. Behavior not considered unsafe | 0 |  |  |
18. Constant evaluation | 44 | 0 | 44 Uncovered rules const-eval const-eval.const-context const-eval.const-context.array-length const-eval.const-context.block const-eval.const-context.general const-eval.const-context.generic const-eval.const-context.init const-eval.const-context.outer-generics const-eval.const-context.repeat-length const-eval.const-expr const-eval.const-expr.array const-eval.const-expr.block const-eval.const-expr.borrows const-eval.const-expr.builtin-arith-logic const-eval.const-expr.cast const-eval.const-expr.closure const-eval.const-expr.const-context const-eval.const-expr.const-fn const-eval.const-expr.constructor const-eval.const-expr.deref const-eval.const-expr.error const-eval.const-expr.evaluation const-eval.const-expr.field const-eval.const-expr.general const-eval.const-expr.group const-eval.const-expr.if-match const-eval.const-expr.index const-eval.const-expr.list const-eval.const-expr.literal const-eval.const-expr.loop const-eval.const-expr.parameter const-eval.const-expr.path-item const-eval.const-expr.path-static const-eval.const-expr.range const-eval.const-expr.runtime-context const-eval.const-expr.tuple const-eval.const-fn const-eval.const-fn.async const-eval.const-fn.body-restriction const-eval.const-fn.const-context const-eval.const-fn.intro const-eval.const-fn.outside-context const-eval.const-fn.type-restrictions const-eval.general | 0.0%
19. Application binary interface | 19 | 0 | 19 Uncovered rules abi abi.export_name abi.export_name.edition2024 abi.export_name.intro abi.export_name.syntax abi.export_name.unsafe abi.intro abi.link_section abi.link_section.edition2024 abi.link_section.intro abi.link_section.syntax abi.link_section.unsafe abi.no_mangle abi.no_mangle.edition2024 abi.no_mangle.intro abi.no_mangle.publicly-exported abi.no_mangle.unsafe abi.used abi.used.intro | 0.0%
20. The Rust runtime | 16 | 0 | 16 Uncovered rules runtime runtime.global_allocator runtime.global_allocator.allowed-positions runtime.global_allocator.duplicates runtime.global_allocator.intro runtime.global_allocator.single runtime.global_allocator.stdlib runtime.global_allocator.syntax runtime.windows_subsystem runtime.windows_subsystem.allowed-positions runtime.windows_subsystem.console runtime.windows_subsystem.duplicates runtime.windows_subsystem.ignored runtime.windows_subsystem.intro runtime.windows_subsystem.syntax runtime.windows_subsystem.windows | 0.0%
21. Appendices | 0 |  |  |
21.1. Grammar summary | 0 |  |  |
21.2. Syntax index | 0 |  |  |
21.3. Macro follow-set ambiguity formal specification | 45 | 0 | 45 Uncovered rules macro.ambiguity macro.ambiguity.convention macro.ambiguity.convention.complex-nt macro.ambiguity.convention.defs macro.ambiguity.convention.matcher macro.ambiguity.convention.sequence-vars macro.ambiguity.convention.set macro.ambiguity.convention.vars macro.ambiguity.invariant macro.ambiguity.invariant.follow-matcher macro.ambiguity.invariant.list macro.ambiguity.invariant.separated-complex-nt macro.ambiguity.invariant.unseparated-complex-nt macro.ambiguity.sets macro.ambiguity.sets.def macro.ambiguity.sets.def.first macro.ambiguity.sets.def.first.complex macro.ambiguity.sets.def.first.epsilon macro.ambiguity.sets.def.first.intro macro.ambiguity.sets.def.first.token macro.ambiguity.sets.def.follow macro.ambiguity.sets.def.follow.expr-stmt macro.ambiguity.sets.def.follow.intro macro.ambiguity.sets.def.follow.other-matcher macro.ambiguity.sets.def.follow.pat macro.ambiguity.sets.def.follow.simple macro.ambiguity.sets.def.follow.ty-path macro.ambiguity.sets.def.follow.type-first macro.ambiguity.sets.def.follow.vis macro.ambiguity.sets.def.intro macro.ambiguity.sets.def.last macro.ambiguity.sets.def.last.delim macro.ambiguity.sets.def.last.empty macro.ambiguity.sets.def.last.intro macro.ambiguity.sets.def.last.rep-plus macro.ambiguity.sets.def.last.rep-question macro.ambiguity.sets.def.last.rep-star macro.ambiguity.sets.def.last.sequence macro.ambiguity.sets.def.last.token macro.ambiguity.sets.def.notation macro.ambiguity.sets.first macro.ambiguity.sets.follow macro.ambiguity.sets.intro macro.ambiguity.sets.last macro.ambiguity.sets.universe | 0.0%
21.4. Influences | 0 |  |  |
21.5. Test summary | 0 |  |  |
21.6. Glossary | 2 | 0 | 2 Uncovered rules glossary.abi glossary.ast | 0.0%
Total: | 2882 | 59 | 2855 | 1.0%

# Glossary

[glossary.ast]

### Abstract syntax tree

An ‘abstract syntax tree’, or ‘AST’, is an intermediate representation of the structure of the program when the compiler is compiling it.

### Alignment

The alignment of a value specifies what addresses values are preferred to start at. Always a power of two. References to a value must be aligned. More.

[glossary.abi]

### Application binary interface (ABI)

An application binary interface (ABI) defines how compiled code interacts with other compiled code. With `extern` blocks and `extern fn`, ABI strings affect:

- Calling convention: How function arguments are passed, values are returned (e.g., in registers or on the stack), and who is responsible for cleaning up the stack.
- Unwinding: Whether stack unwinding is allowed. For example, the `"C-unwind"` ABI allows unwinding across the FFI boundary, while the `"C"` ABI does not.

### Arity

Arity refers to the number of arguments a function or operator takes. For some examples, `f(2, 3)` and `g(4, 6)` have arity 2, while `h(8, 2, 6)` has arity 3. The `!` operator has arity 1.

### Array

An array, sometimes also called a fixed-size array or an inline array, is a value describing a collection of elements, each selected by an index that can be computed at run time by the program. It occupies a contiguous region of memory.

### Associated item

An associated item is an item that is associated with another item. Associated items are defined in implementations and declared in traits. Only functions, constants, and type aliases can be associated. Contrast to a free item.

### Blanket implementation

Any implementation where a type appears uncovered. `impl<T> Foo for T`, `impl<T> Bar<T> for T`, `impl<T> Bar<Vec<T>> for T`, and `impl<T> Bar<T> for Vec<T>` are considered blanket impls. However, `impl<T> Bar<Vec<T>> for Vec<T>` is not a blanket impl, as all instances of `T` which appear in this `impl` are covered by `Vec`.

### Bound

Bounds are constraints on a type or trait. For example, if a bound is placed on the argument a function takes, types passed to that function must abide by that constraint.

### Combinator

Combinators are higher-order functions that apply only functions and earlier defined combinators to provide a result from its arguments. They can be used to manage control flow in a modular fashion.

### Crate

A crate is the unit of compilation and linking. There are different types of crates, such as libraries or executables. Crates may link and refer to other library crates, called external crates. A crate has a self-contained tree of modules, starting from an unnamed root module called the crate root. Items may be made visible to other crates by marking them as public in the crate root, including through paths of public modules. More.

### Dispatch

Dispatch is the mechanism to determine which specific version of code is actually run when it involves polymorphism. Two major forms of dispatch are static dispatch and dynamic dispatch. Rust supports dynamic dispatch through the use of trait objects.

### Dynamically sized type

A dynamically sized type (DST) is a type without a statically known size or alignment.

### Entity

An entity is a language construct that can be referred to in some way within the source program, usually via a path. Entities include types, items, generic parameters, variable bindings, loop labels, lifetimes, fields, attributes, and lints.

### Expression

An expression is a combination of values, constants, variables, operators and functions that evaluate to a single value, with or without side-effects.

For example, `2 + (3 * 4)` is an expression that returns the value 14.

### Free item

An item that is not a member of an implementation, such as a free function or a free const. Contrast to an associated item.

### Fundamental traits

A fundamental trait is one where adding an impl of it for an existing type is a breaking change. The `Fn` traits and `Sized` are fundamental.

### Fundamental type constructors

A fundamental type constructor is a type where implementing a blanket implementation over it is a breaking change. `&`, `&mut`, `Box`, and `Pin` are fundamental.

Any time a type `T` is considered local, `&T`, `&mut T`, `Box<T>`, and `Pin<T>` are also considered local. Fundamental type constructors cannot cover other types. Any time the term “covered type” is used, the `T` in `&T`, `&mut T`, `Box<T>`, and `Pin<T>` is not considered covered.

### Inhabited

A type is inhabited if it has constructors and therefore can be instantiated. An inhabited type is not “empty” in the sense that there can be values of the type. Opposite of Uninhabited.

### Inherent implementation

An implementation that applies to a nominal type, not to a trait-type pair. More.

### Inherent method

A method defined in an inherent implementation, not in a trait implementation.

### Initialized

A variable is initialized if it has been assigned a value and hasn’t since been moved from. All other memory locations are assumed to be uninitialized. Only unsafe Rust can create a memory location without initializing it.

### Local trait

A `trait` which was defined in the current crate. A trait definition is local or not independent of applied type arguments. Given `trait Foo<T, U>`, `Foo` is always local, regardless of the types substituted for `T` and `U`.

### Local type

A `struct`, `enum`, or `union` which was defined in the current crate. This is not affected by applied type arguments. `struct Foo` is considered local, but `Vec<Foo>` is not. `LocalType<ForeignType>` is local. Type aliases do not affect locality.

### Module

A module is a container for zero or more items. Modules are organized in a tree, starting from an unnamed module at the root called the crate root or the root module. Paths may be used to refer to items from other modules, which may be restricted by visibility rules. More

### Name

A name is an identifier or lifetime or loop label that refers to an entity. A name binding is when an entity declaration introduces an identifier or label associated with that entity. Paths, identifiers, and labels are used to refer to an entity.

### Name resolution

Name resolution is the compile-time process of tying paths, identifiers, and labels to entity declarations.

### Namespace

A namespace is a logical grouping of declared names based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.

Within a namespace, names are organized in a hierarchy, where each level of the hierarchy has its own collection of named entities.

### Nominal types

Types that can be referred to by a path directly. Specifically enums, structs, unions, and trait object types.

### Dyn-compatible traits

Traits that can be used in trait object types (`dyn Trait`). Only traits that follow specific rules are dyn compatible.

These were formerly known as object safe traits.

### Path

A path is a sequence of one or more path segments used to refer to an entity in the current scope or other levels of a namespace hierarchy.

### Prelude

Prelude, or The Rust Prelude, is a small collection of items - mostly traits - that are imported into every module of every crate. The traits in the prelude are pervasive.

### Scope

A scope is the region of source text where a named entity may be referenced with that name.

### Scrutinee

A scrutinee is the expression that is matched on in `match` expressions and similar pattern matching constructs. For example, in `match x { A => 1, B => 2 }`, the expression `x` is the scrutinee.

### Size

The size of a value has two definitions.

The first is that it is how much memory must be allocated to store that value.

The second is that it is the offset in bytes between successive elements in an array with that item type.

It is a multiple of the alignment, including zero. The size can change depending on compiler version (as new optimizations are made) and target platform (similar to how `usize` varies per-platform).

More.

### Slice

A slice is dynamically-sized view into a contiguous sequence, written as `[T]`.

It is often seen in its borrowed forms, either mutable or shared. The shared slice type is `&[T]`, while the mutable slice type is `&mut [T]`, where `T` represents the element type.

### Statement

A statement is the smallest standalone element of a programming language that commands a computer to perform an action.

### String literal

A string literal is a string stored directly in the final binary, and so will be valid for the `'static` duration.

Its type is `'static` duration borrowed string slice, `&'static str`.

### String slice

A string slice is the most primitive string type in Rust, written as `str`. It is often seen in its borrowed forms, either mutable or shared. The shared string slice type is `&str`, while the mutable string slice type is `&mut str`.

Strings slices are always valid UTF-8.

### Trait

A trait is a language item that is used for describing the functionalities a type must provide. It allows a type to make certain promises about its behavior.

Generic functions and generic structs can use traits to constrain, or bound, the types they accept.

### Turbofish

Paths with generic parameters in expressions must prefix the opening brackets with a `::`. Combined with the angular brackets for generics, this looks like a fish `::<>`. As such, this syntax is colloquially referred to as turbofish syntax.

Examples:

    #![allow(unused)]
    fn main() {
    let ok_num = Ok::<_, ()>(5);
    let vec = [1, 2, 3].iter().map(|n| n * 2).collect::<Vec<_>>();
    }

This `::` prefix is required to disambiguate generic paths with multiple comparisons in a comma-separate list. See the bastion of the turbofish for an example where not having the prefix would be ambiguous.

### Uncovered type

A type which does not appear as an argument to another type. For example, `T` is uncovered, but the `T` in `Vec<T>` is covered. This is only relevant for type arguments.

### Undefined behavior

Compile-time or run-time behavior that is not specified. This may result in, but is not limited to: process termination or corruption; improper, incorrect, or unintended computation; or platform-specific results. More.

### Uninhabited

A type is uninhabited if it has no constructors and therefore can never be instantiated. An uninhabited type is “empty” in the sense that there are no values of the type. The canonical example of an uninhabited type is the never type `!`, or an enum with no variants `enum Never { }`. Opposite of Inhabited.