The Rust Reference › Use declarations › Underscore imports

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.
```rust
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();
}
```
Asterisk glob imports will import items imported with `_` in their unnameable form.
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:
```rust
macro_rules! m {
    ($item: item) => { $item $item }
}

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


The Rust Reference › Use declarations › Restrictions

The following rules are restrictions for valid `use` declarations.
When using `crate` to import the current crate, you must use `as` to define the binding name.
```rust
use crate as root;
use crate::{self as root2};

// Not allowed:
// use crate;
// use crate::{self};
```
When using [`$crate`] in a macro transcriber to import the current crate, you must use `as` to define the binding name.
```rust
macro_rules! import_crate_root {
    () => {
        use $crate as my_crate;
        use $crate::{self as my_crate2};
    };
}
```
When using `self` to import the current module, you must use `as` to define the binding name.
```rust
use {self as this_module};
use self as this_module2;
use self::{self as this_module3};

// Not allowed:
// use {self};
// use self;
// use self::{self};
```
When using `super` to import a parent module, you must use `as` to define the binding name.
```rust
mod a {
    mod b {
        use super as parent;
        use super::{self as parent2};
        use self::super as parent3;
        use super::super as grandparent;
        use super::super::{self as grandparent2};

        // Not allowed:
        // use super;
        // use super::{self};
        // use self::super;
        // use super::super;
        // use super::super::{self};
    }
}
```
`::` as the [extern prelude] cannot be imported.
```rust,edition2018,compile_fail
use ::{self as root}; //~ Error
```


The Rust Reference › Use declarations › Restrictions

[!EDITION-2018]
In the 2015 edition, the prefix `::` refers to the crate root, so `use ::{self as root};` is allowed because it is same as `use crate::{self as root};`. Starting with the 2018 edition the `::` prefix refers to the extern prelude, which cannot be directly imported.
```rust,edition2015
use ::{self as root}; //~ Ok
```
As with any item definition, `use` imports cannot create duplicate bindings of the same name in the same namespace in a module or block.
`use` paths cannot refer to enum variants through a [type alias].
```rust,compile_fail
enum MyEnum {
  MyVariant
}
type TypeAlias = MyEnum;

use MyEnum::MyVariant; //~ OK
use TypeAlias::MyVariant; //~ ERROR
```


The Rust Reference › Functions

```grammar,items
Function ->
    FunctionQualifiers `fn` IDENTIFIER GenericParams?
        `(` FunctionParameters? `)`
        FunctionReturnType? WhereClause?
        ( BlockExpression | `;` )

FunctionQualifiers -> `const`? `async`?[^async-edition] ItemSafety?[^extern-qualifiers] (`extern` Abi?)?

ItemSafety -> `safe`[^extern-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[^fn-param-2015] )

FunctionParamPattern -> PatternNoTopAlt `:` ( Type | `...` )

FunctionReturnType -> `->` Type
```
[^async-edition]: The `async` qualifier is not allowed in the 2015 edition.
[^extern-safe]: The `safe` function qualifier is only allowed semantically within `extern` blocks.
[^extern-qualifiers]: *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`.
[^fn-param-2015]: Function parameters with only a type are only allowed in an associated function of a [trait item] in the 2015 edition.
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.


The Rust Reference › Functions

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.
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.
If the output type is not explicitly stated, it is the [unit 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:
```rust
fn answer_to_life_the_universe_and_everything() -> i32 {
    return 42;
}
```
The `safe` function is semantically only allowed when used in an [`extern` block].


The Rust Reference › Functions › Function parameters

Function parameters are irrefutable [patterns], so any pattern that is valid in an else-less `let` binding is also valid as a parameter:
```rust
fn first((value, _): (i32, i32)) -> i32 { value }
```
If the first parameter is a [SelfParam], this indicates that the function is a [method].
Functions with a self parameter may only appear as an [associated function] in a [trait] or [implementation].
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: ...`.


The Rust Reference › Functions › Function body

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:
```rust,ignore
// argument_0 is the actual first argument passed from the caller
let (value, _) = argument_0;
return {
    value
};
```
Functions without a body block are terminated with a semicolon. This form may only appear in a [trait] or [external block].


The Rust Reference › Functions › Generic functions

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.
```rust
// foo is generic over A and B

fn foo<A, B>(x: A, y: B) {
```
Inside the function signature and body, the name of the type parameter can be used as a type name.
[Trait] bounds can be specified for type parameters to allow methods from that trait to be called on values of that type. This is specified using the `where` syntax:
```rust
fn foo<T>(x: T) where T: Debug {
```
When a generic function is referenced, its type is instantiated based on the context of the reference. For example, calling the `foo` function here:
```rust
use std::fmt::Debug;

fn foo<T>(x: &[T]) where T: Debug {
    // details elided
}

foo(&[1, 2]);
```
will instantiate type parameter `T` with `i32`.
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`.


The Rust Reference › Functions › Extern function qualifier

The `extern` function qualifier allows providing function _definitions_ that can be called with a particular ABI:
```rust,ignore
extern "ABI" fn foo() { /* ... */ }
```
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_:
```rust,ignore
unsafe extern "ABI" {
  unsafe fn foo(); /* no body */
  safe fn bar(); /* no body */
}
unsafe { foo() };
bar();
```
When `"extern" Abi?*` is omitted from `FunctionQualifiers` in function items, the ABI `"Rust"` is assigned. For example:
```rust
fn foo() {}
```
is equivalent to:
```rust
extern "Rust" fn foo() {}
```
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:
```rust
// Declares a function with the "C" ABI
extern "C" fn new_i32() -> i32 { 0 }

// Declares a function with the "stdcall" ABI
extern "stdcall" fn new_i32_stdcall() -> i32 { 0 }
```
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:
```rust
extern fn new_i32() -> i32 { 0 }
let fptr: extern fn() -> i32 = new_i32;
```
is equivalent to:
```rust
extern "C" fn new_i32() -> i32 { 0 }
let fptr: extern "C" fn() -> i32 = new_i32;
```


The Rust Reference › Functions › Extern function qualifier › Unwinding

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.
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.

Functions
Extern function qualifier
Unwinding


The Rust Reference › Functions › Extern function qualifier › Unwinding

| 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]     |
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.


The Rust Reference › Functions › Const functions

See [const functions] for the definition of const functions.


The Rust Reference › Functions › Async functions

Functions may be qualified as async, and this can also be combined with the `unsafe` qualifier:
```rust
async fn regular_example() { }
async unsafe fn unsafe_example() { }
```
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.
An async function is roughly equivalent to a function that returns [`impl Future`] and with an `async move` block as its body:
```rust
// Source
async fn example(x: &str) -> usize {
    x.len()
}
```
is roughly equivalent to:
```rust
// Desugared
fn example<'a>(x: &'a str) -> impl Future<Output = usize> + 'a {
    async move { x.len() }
}
```
The actual desugaring is more complex:
- 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`.
- 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.
[!EDITION-2018]
Async functions are only available beginning with Rust 2018.


The Rust Reference › Functions › Async functions › Combining `async` and `unsafe`

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:
```rust
// 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.

Functions
Async functions
Combining `async` and `unsafe`


The Rust Reference › Functions › Attributes on functions

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".
```rust
fn documented() {
    #![doc = "Example"]
}
```
Except for lints, it is idiomatic to only use outer attributes on function items.
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]


The Rust Reference › Functions › Attributes on function parameters

Outer attributes are allowed on function parameters and the permitted [built-in attributes] are restricted to `cfg`, `cfg_attr`, `allow`, `warn`, `deny`, and `forbid`.
```rust
fn len(
    #[cfg(windows)] slice: &[u16],
    #[cfg(not(windows))] slice: &[u8],
) -> usize {
    slice.len()
}
```
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.
```rust,ignore
#[some_proc_macro_attribute]
fn foo_oof(#[some_inert_attribute] arg: u8) {
}
```

Functions
Attributes on function parameters


The Rust Reference › Type aliases

```grammar,items
TypeAlias ->
    `type` IDENTIFIER GenericParams? ( `:` Bounds? )?
        WhereClause?
        ( `=` Type WhereClause?)? `;`
```
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:
```rust
type Point = (u8, u8);
let p: Point = (41, 68);
```
A type alias to a tuple-struct or unit-struct cannot be used to qualify that type's constructor:
```rust,compile_fail
struct MyStruct(u32);

use MyStruct as UseAlias;
type TypeAlias = MyStruct;

let _ = UseAlias(5); // OK
let _ = TypeAlias(5); // Doesn't work
```
A type alias, when not used as an [associated type], must include a Type and may not include [Bounds].
A type alias, when used as an [associated type] in a [trait], must not include a Type specification but may include [Bounds].
A type alias, when used as an [associated type] in a [trait impl], must include a Type specification and may not include [Bounds].
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.


The Rust Reference › Structs

```grammar,items
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
```
A _struct_ is a nominal [struct type] defined with the keyword `struct`.
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:
```rust
struct Point {x: i32, y: i32}
let p = Point {x: 10, y: 11};
let px: i32 = p.x;
```
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:
```rust
struct Point(i32, i32);
let p = Point(10, 11);
let px: i32 = match p { Point(x, _) => x };
```
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:
```rust
struct Cookie;
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
```
is equivalent to


The Rust Reference › Structs

```rust
struct Cookie {}
const Cookie: Cookie = Cookie {};
let c = [Cookie, Cookie {}, Cookie, Cookie {}];
```
The precise memory layout of a struct is not specified. One can specify a particular layout using the [`repr` attribute].


The Rust Reference › Enumerations

```grammar,items
Enumeration ->
    `enum` IDENTIFIER GenericParams? WhereClause? `{` EnumVariants? `}`

EnumVariants -> EnumVariant ( `,` EnumVariant )* `,`?

EnumVariant ->
    OuterAttribute* Visibility?
    IDENTIFIER ( EnumVariantTuple | EnumVariantStruct )? EnumVariantDiscriminant?

EnumVariantTuple -> `(` TupleFields? `)`

EnumVariantStruct -> `{` StructFields? `}`

EnumVariantDiscriminant -> `=` Expression
```
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.
Enumerations are declared with the keyword `enum`.
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:
```rust
enum Animal {
    Dog,
    Cat,
}

let mut a: Animal = Animal::Dog;
a = Animal::Cat;
```
Enum constructors can have either named or unnamed fields:
```rust
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.
An enum where no constructors contain fields is called a *field-less enum*. For example, this is a fieldless enum:
```rust
enum Fieldless {
    Tuple(),
    Struct{},
    Unit,
}
```


The Rust Reference › Enumerations

If a field-less enum only contains unit variants, the enum is called an *unit-only enum*. For example:
```rust
enum Enum {
    Foo = 3,
    Bar = 2,
    Baz = 1,
}
```
Variant constructors are similar to [struct] definitions, and can be referenced by a path from the enumeration name, including in [use declarations].
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].
A struct-like variant can be instantiated with a [struct expression].
A tuple-like variant can be instantiated with a [call expression] or a [struct expression].
A unit-like variant can be instantiated with a [path expression] or a [struct expression]. For example:
```rust
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.
```


The Rust Reference › Enumerations › Discriminants

Each enum instance has a _discriminant_: an integer logically associated to it that is used to determine which variant it holds.
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.


The Rust Reference › Enumerations › Discriminants › Assigning discriminant values › Restrictions

In two circumstances, the discriminant of a variant may be explicitly set by following the variant name with `=` and a [constant expression]:
1. if the enumeration is "[unit-only]".
2. if a [primitive representation] is used. For example:
```rust
   #[repr(u8)]
   enum Enum {
       Unit = 3,
       Tuple(u16),
       Struct {
           a: u8,
           b: u16,
       } = 1,
   }
```
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.
```rust
enum Foo {
    Bar,            // 0
    Baz = 123,      // 123
    Quux,           // 124
}

let baz_discriminant = Foo::Baz as u32;
assert_eq!(baz_discriminant, 123);
```
It is an error when two variants share the same discriminant.
```rust,compile_fail
enum SharedDiscriminantError {
    SharedA = 1,
    SharedB = 1,
}

enum SharedDiscriminantError2 {
    Zero,       // 0
    One,        // 1
    OneToo = 1, // 1 (collision with previous!)
}
```
It is also an error to have an unspecified discriminant where the previous discriminant is the maximum value for the size of the discriminant.

Enumerations
Discriminants
Assigning discriminant values
Restrictions


The Rust Reference › Enumerations › Discriminants › Assigning discriminant values › Restrictions

```rust,compile_fail
#[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.
}
```
Explicit enum discriminant initializers may not use generic parameters from the enclosing enum.
```rust,compile_fail
#[repr(u32)]
enum E<'a, T, const N: u32> {
    Lifetime(&'a T) = {
        let a: &'a (); // ERROR.
        1
    },
    Type(T) = {
        let x: T; // ERROR.
        2
    },
    Const = N, // ERROR.
}
```


The Rust Reference › Enumerations › Discriminants › Accessing discriminant › Pointer casting

[`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.
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.:
```rust
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);
```
[Field-less enums] can be cast if they do not have explicit discriminants, or where only unit variants are explicit.
```rust
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);
```
If the enumeration specifies a [primitive representation], then the discriminant may be reliably accessed via unsafe pointer casting:

Enumerations
Discriminants
Accessing discriminant
Pointer casting


The Rust Reference › Enumerations › Discriminants › Accessing discriminant › Pointer casting

```rust
#[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());
```


The Rust Reference › Enumerations › Zero-variant enums

Enums with zero variants are known as *zero-variant enums*. As they have no valid values, they cannot be instantiated.
```rust
enum ZeroVariants {}
```
Zero-variant enums are equivalent to the [never type], but they cannot be coerced into other types.
```rust,compile_fail
let x: ZeroVariants = panic!();
let y: u32 = x; // mismatched type error
```


The Rust Reference › Enumerations › 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.
```rust
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 },
}
```


The Rust Reference › Unions

```grammar,items
Union ->
    `union` IDENTIFIER GenericParams? WhereClause? `{` StructFields? `}`
```
A union declaration uses the same syntax as a struct declaration, except with `union` in place of `struct`.
A union declaration defines the given name in the [type namespace] of the module or block where it is located.
```rust
#[repr(C)]
union MyUnion {
    f1: u32,
    f2: f32,
}
```
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.
Union field types are restricted to the following subset of types:
- `Copy` types
- References (`&T` and `&mut T` for arbitrary `T`)
- `ManuallyDrop<T>` (for arbitrary `T`)
- Tuples and arrays containing only allowed union field types
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.
Unions without any fields are not accepted by the compiler, but can be accepted by macros.


The Rust Reference › Unions › Initialization of a union

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:
```rust
let u = MyUnion { f1: 1 };
```
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:
```rust
let f = unsafe { u.f1 };
```


The Rust Reference › Unions › Reading and writing union fields

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.
Reading a union field reads the bits of the union at the field's type.
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
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.
Consequently, all reads of union fields have to be placed in `unsafe` blocks:
```rust
unsafe {
    let f = u.f1;
}
```
Commonly, code using unions will provide safe wrappers around unsafe union field accesses.
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.)


The Rust Reference › Unions › Pattern matching on unions

Another way to access union fields is to use pattern matching.
Pattern matching on union fields uses the same syntax as struct patterns, except that the pattern must specify exactly one field.
Since pattern matching is like reading the union with a particular field, it has to be placed in `unsafe` blocks as well.
```rust
fn f(u: MyUnion) {
    unsafe {
        match u {
            MyUnion { f1: 10 } => { println!("ten"); }
            MyUnion { f2 } => { println!("{}", f2); }
        }
    }
}
```
The order in which the subpatterns of a pattern are tested is not specified. A union field named in a pattern may be read even when the pattern as a whole does not match. Reading a union field is undefined behavior unless it holds a valid value of its type (see [items.union.fields.validity]). Nothing else in the pattern can be relied on to prevent the read.
In particular, when implementing a C-style tagged union, avoid matching the tag and the corresponding union field within a single pattern: the union field may be read even when the tag does not match.
To read a union field only when a condition holds, test the condition and read the field in separate steps whose evaluation order is specified. For a C tagged union, match on the tag first and read the union field within the matched arm:
```rust
#[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 {
    match v.tag {
        Tag::I => unsafe { v.u.i == 0 },
        Tag::F => unsafe { v.u.f == 0.0 },
    }
}
```


The Rust Reference › Unions › References to union fields

Since union fields share common storage, gaining write access to one field of a union can give write access to all its remaining fields.
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.
```rust,compile_fail
// 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);
}
```
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).


The Rust Reference › Constant items

```grammar,items
ConstantItem ->
    `const` ( IDENTIFIER | `_` ) `:` Type ( `=` Expression )? `;`
```
A *constant item* is an optionally named _[constant value]_ which is not associated with a specific memory location in the program.
Constants are essentially inlined wherever they are used, meaning that they are copied directly into the relevant context when used. This includes use 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.
The constant declaration defines the constant value in the [value namespace] of the module or block where it is located.
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].
A reference to a constant will have `'static` lifetime if the constant value is eligible for [promotion]; otherwise, a temporary will be created.
```rust
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,
};
```
The constant expression may only be omitted in a [trait definition].


The Rust Reference › Constant items › Constants with destructors

Constants can contain destructors. Destructors are run when the value goes out of scope.
```rust
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.".
}
```

Constant items
Constants with destructors


The Rust Reference › Constant items › Unnamed constant

Unlike an [associated constant], a [free] constant may be unnamed by using an underscore instead of the name. For example:
```rust
const _: () =  { struct _SameNameTwice; };

// OK although it is the same name as above:
const _: () =  { struct _SameNameTwice; };
```
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:
```rust
macro_rules! m {
    ($item: item) => { $item $item }
}

m!(const _: () = (););
// This expands to:
// const _: () = ();
// const _: () = ();
```


The Rust Reference › Constant items › Evaluation

Free constants are always evaluated at compile-time to surface panics. This happens even within an unused function:
```rust,compile_fail
// Compile-time panic
const PANIC: () = std::unimplemented!();

fn unused_generic_function<T>() {
    // A failing compile-time assertion
    const _: () = assert!(usize::BITS == 0);
}
```


The Rust Reference › Static items

```grammar,items
StaticItem ->
    ItemSafety?[^extern-safety] `static` `mut`? IDENTIFIER `:` Type ( `=` Expression )? `;`
```
[^extern-safety]: The `safe` and `unsafe` function qualifiers are only allowed semantically within `extern` blocks.
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.
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.
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.
The static declaration defines a static value in the [value namespace] of the module or block where it is located.
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.
Non-`mut` static items that contain a type that is not [interior mutable] may be placed in read-only memory.
All access to a static is safe, but there are a number of restrictions on statics:
* The type must have the `Sync` trait bound to allow thread-safe access.
The initializer expression must be omitted in an [external block], and must be provided for free static items.
The `safe` and `unsafe` qualifiers are semantically only allowed when used in an [external block].


The Rust Reference › Static items › 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:
```rust
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
```text
default_impl: counter was 0
default_impl: counter was 1
blanket_impl: counter was 0
blanket_impl: counter was 1
```


The Rust Reference › Static items › Mutable statics

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.
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.
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.
```rust

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);
    }
}
```
Mutable statics have the same restrictions as normal statics, except that the type does not have to implement the `Sync` trait.


The Rust Reference › Static items › 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.


The Rust Reference › Traits

```grammar,items
Trait ->
    `unsafe`? `trait` IDENTIFIER GenericParams? ( `:` Bounds? )? WhereClause?
    `{`
        InnerAttribute*
        AssociatedItem*
    `}`
```
A _trait_ describes an abstract interface that types can implement. This interface consists of [associated items], which come in three varieties:
- functions
- types
- constants
The trait declaration defines a trait in the [type namespace] of the module or block where it is located.
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.
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.
Traits are implemented for specific types through separate [implementations].
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 equal 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.
```rust
// 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) {}
}
```
Trait functions are not allowed to be [`const`].


The Rust Reference › Traits › Trait bounds

Generic items may use traits as [bounds] on their type parameters.


The Rust Reference › Traits › 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].
```rust
trait Seq<T> {
    fn len(&self) -> u32;
    fn elt_at(&self, n: u32) -> T;
    fn iter<F>(&self, f: F) where F: Fn(T);
}
```


The Rust Reference › Traits › Dyn compatibility

A dyn-compatible trait can be the base trait of a [trait object]. A trait is *dyn compatible* if it has the following qualities:
* All [supertraits] must also be dyn compatible.
* `Sized` must not be a supertrait. In other words, it must not require `Self: Sized`.
* It must not have any associated constants.
* It must not have any associated types with generics.
* 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).
* The [`AsyncFn`], [`AsyncFnMut`], and [`AsyncFnOnce`] traits are not dyn-compatible.
This concept was formerly known as *object safety*.


The Rust Reference › Traits › Dyn compatibility

```rust
// 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>>) {}
}
```
```rust,compile_fail
// 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
```


The Rust Reference › Traits › Dyn compatibility

```rust,compile_fail
// 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
```
```rust,compile_fail
// `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
```
```rust,compile_fail
// 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
```


The Rust Reference › Traits › Supertraits

**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.
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.
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`.
```rust
trait Shape { fn area(&self) -> f64; }
trait Circle: Shape { fn radius(&self) -> f64; }
```
And the following is the same example, except using [where clauses].
```rust
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`.
```rust
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.
```rust
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.


The Rust Reference › Traits › Supertraits

```rust
let circle = Box::new(circle) as Box<dyn Circle>;
let nonsense = circle.radius() * circle.area();
```


The Rust Reference › Traits › Unsafe traits

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.


The Rust Reference › Traits › Parameter patterns

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.
```rust
trait T {
    fn f1(&self);
    fn f2(x: Self, _: i32);
}
```
```rust,compile_fail,E0642
trait T {
    fn f2(&x: &i32); // ERROR: patterns aren't allowed in functions without bodies
}
```
Parameters in associated functions with a body only allow irrefutable patterns.
```rust
trait T {
    fn f1((a, b): (i32, i32)) {} // OK: is irrefutable
}
```
```rust,compile_fail,E0005
trait T {
    fn f1(123: i32) {} // ERROR: pattern is refutable
    fn f2(Some(x): Option<i32>) {} // ERROR: pattern is refutable
}
```
[!EDITION-2018]
Prior to the 2018 edition, the pattern for an associated function parameter is optional:
```rust,edition2015
// 2015 Edition
trait T {
    fn f(i32); // OK: parameter identifiers are not required
}
```
Beginning in the 2018 edition, patterns are no longer optional.
[!EDITION-2018]
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]


The Rust Reference › Traits › Parameter patterns

```rust,edition2015,compile_fail,E0642
// 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].


The Rust Reference › Traits › Item visibility

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.
```rust
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();
}
```


The Rust Reference › Implementations

```grammar,items
Implementation -> InherentImpl | TraitImpl

InherentImpl ->
    `impl` GenericParams? Type WhereClause? `{`
        InnerAttribute*
        AssociatedItem*
    `}`

TraitImpl ->
    `unsafe`? `impl` GenericParams? `!`? TypePath `for` Type
    WhereClause?
    `{`
        InnerAttribute*
        AssociatedItem*
    `}`
```
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.
There are two types of implementations:
- inherent implementations
- [trait] implementations


The Rust Reference › Implementations › Inherent implementations

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.
The nominal type is called the _implementing type_ and the associable items are the _associated items_ to the implementing type.
Inherent implementations associate the contained items to the implementing type.
Inherent implementations can contain [associated functions] (including [methods]) and [associated constants].
They cannot contain associated type aliases.
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.
A type can also have multiple inherent implementations. An implementing type must be defined within the same crate as the original type definition.
``` rust
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();
}
```


The Rust Reference › Implementations › Trait implementations

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.
The trait is known as the _implemented trait_. The implementing type implements the implemented trait.
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.
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.
[Unsafe traits] require the trait implementation to begin with the `unsafe` keyword.
```rust
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,
        }
    }
}
```


The Rust Reference › Implementations › Trait implementations › Trait implementation coherence › Orphan rules

A trait implementation is considered incoherent if either the orphan rules check fails or there are overlapping implementation instances.
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.
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.
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`)
Only the appearance of *uncovered* type parameters is restricted.
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.

Implementations
Trait implementations
Trait implementation coherence
Orphan rules


The Rust Reference › Implementations › Generic implementations

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.
```rust
impl<T> Seq<T> for Vec<T> {
    /* ... */
}
impl Seq<bool> for u32 {
    /* Treat the integer as a sequence of bits */
}
```
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
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:
```rust
// 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:


The Rust Reference › Implementations › Generic implementations

```rust,compile_fail
// 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:
```rust
impl<'a> Struct {}
```
Example of a disallowed unconstraining lifetime parameter:
```rust,compile_fail
impl<'a> HasAssocType for Struct {
    type Ty = &'a Struct;
}
```


The Rust Reference › Implementations › 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].

Implementations
Attributes on implementations


The Rust Reference › External blocks

```grammar,items
ExternBlock ->
    `unsafe`?[^unsafe-2024] `extern` Abi? `{`
        InnerAttribute*
        ExternalItem*
    `}`

ExternalItem ->
    OuterAttribute* (
        MacroInvocationSemi
      | Visibility? StaticItem
      | Visibility? Function
    )
```
[^unsafe-2024]: Starting with the 2024 Edition, the `unsafe` keyword is required semantically.
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.
Two kinds of item _declarations_ are allowed in external blocks: [functions] and [statics].
Calling unsafe functions or accessing unsafe statics that are declared in external blocks is only allowed in an [`unsafe` context].
The external block defines its functions and statics in the [value namespace] of the module or block where it is located.
The `unsafe` keyword is semantically required to appear before the `extern` keyword on external blocks.
[!EDITION-2024]
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`.


The Rust Reference › External blocks › Functions

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.
Patterns are not allowed in parameters, only [IDENTIFIER] or `_` may be used.
The `safe` and `unsafe` function qualifiers are allowed, but other function qualifiers (e.g. `const`, `async`, `extern`) are not.
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.
A function declared in an extern block is implicitly `unsafe` unless the `safe` function qualifier is present.
When coerced to a function pointer, a function declared in an extern block has type `for<'l1, ..., 'lm> extern "abi" 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.


The Rust Reference › External blocks › Statics

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.
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.
Extern statics can be either immutable or mutable just like [statics] outside of external blocks.
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`.


The Rust Reference › External blocks › ABI

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.
```rust
// Interface to the Windows API.
unsafe extern "system" { /* ... */ }
```
If the ABI string is not specified, it defaults to `"C"`.
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.
The following ABI strings are supported on all platforms:
* `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.
* `unsafe extern "C"` --- The "C" ABI matches the default ABI chosen by the dominant C compiler for the target.
* `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.
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.
* `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).


The Rust Reference › External blocks › ABI

There are also some platform-specific ABI strings:
* `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))`.
For details, see:
- <https://learn.microsoft.com/en-us/cpp/cpp/cdecl>
- <https://en.wikipedia.org/wiki/X86_calling_conventions#cdecl>
* `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))`.
For details, see:
- <https://learn.microsoft.com/en-us/cpp/cpp/stdcall>
- <https://en.wikipedia.org/wiki/X86_calling_conventions#stdcall>
* `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))`.
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>


The Rust Reference › External blocks › ABI

* `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))`.
For details, see:
- <https://wiki.osdev.org/System_V_ABI>
- <https://en.wikipedia.org/wiki/X86_calling_conventions#System_V_AMD64_ABI>
* `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")))`.
For details, see:
- Arm Procedure Call Standard
* `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))`.
For details, see:
- <https://learn.microsoft.com/en-us/cpp/cpp/fastcall>
- <https://en.wikipedia.org/wiki/X86_calling_conventions#Microsoft_fastcall>


The Rust Reference › External blocks › ABI

* `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))`.
For details, see:
- <https://en.wikipedia.org/wiki/X86_calling_conventions#thiscall>
- <https://learn.microsoft.com/en-us/cpp/cpp/thiscall>
* `unsafe extern "efiapi"` --- The ABI used for [UEFI] functions.
  * Only available on x86 and ARM targets (32bit and 64bit).
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"`


The Rust Reference › External blocks › 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.
```rust
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, ...);
}
```
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.
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"`


The Rust Reference › External blocks › Attributes on extern blocks

The following [attributes] control the behavior of external blocks.

External blocks
Attributes on extern blocks


The Rust Reference › External blocks › Attributes on extern blocks › The `link` attribute

The *`link` attribute* specifies the name of a native library that the compiler should link with for the items within an `extern` block.
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:
- `dylib` --- Indicates a dynamic library. This is the default if `kind` is not specified.
- `static` --- Indicates a static library.
- `framework` --- Indicates a macOS framework. This is only valid for macOS targets.
- `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.
The `name` key must be included if `kind` is specified.
The optional `modifiers` argument is a way to specify linking modifiers for the library to link.
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.
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")]`.
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.

External blocks
Attributes on extern blocks
The `link` attribute


The Rust Reference › External blocks › Attributes on extern blocks › The `link` attribute › Linking modifiers: `whole-archive`

```rust,ignore
#[link(name = "crypto")]
unsafe extern {
    // …
}

#[link(name = "CoreFoundation", kind = "framework")]
unsafe extern {
    // …
}

#[link(wasm_import_module = "foo")]
unsafe extern {
    // …
}
```
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.
This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.
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.
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.
This modifier has no effect when building other targets like executables or dynamic libraries.
The default for this modifier is `+bundle`.
More implementation details about this modifier can be found in [`bundle` documentation for rustc].
This modifier is only compatible with the `static` linking kind. Using any other kind will result in a compiler error.
`+whole-archive` means that the static library is linked as a whole archive without throwing any object files away.
The default for this modifier is `-whole-archive`.
More implementation details about this modifier can be found in [`whole-archive` documentation for rustc].

External blocks
Attributes on extern blocks
The `link` attribute
Linking modifiers: `whole-archive`


The Rust Reference › External blocks › Attributes on extern blocks › Linking modifiers: `verbatim` › The `import_name_type` key

This modifier is compatible with all linking kinds.
`+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.
`-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.
The default for this modifier is `-verbatim`.
More implementation details about this modifier can be found in [`verbatim` documentation for rustc].
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.
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.
`raw-dylib` is only supported on Windows. Using it when targeting other platforms will result in a compiler error.

External blocks
Attributes on extern blocks
Linking modifiers: `verbatim`
The `import_name_type` key


The Rust Reference › External blocks › Attributes on extern blocks › Linking modifiers: `verbatim` › The `import_name_type` key

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.
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.
If the `import_name_type` key is not specified, then the function name will be fully-decorated using the target toolchain's format.
Variables are never decorated and so the `import_name_type` key has no effect on how they are named in the generated import library.
The `import_name_type` key is only supported on x86 Windows. Using it when targeting other platforms will result in a compiler error.


The Rust Reference › External blocks › Attributes on extern blocks › The `link_name` attribute

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.
```rust
unsafe extern "C" {
    #[link_name = "actual_symbol_name"]
    safe fn name_in_rust();
}
```
The `link_name` attribute uses the [MetaNameValueStr] syntax.
The symbol name must not be the empty string or contain any `U+0000` (NUL) bytes.
The `link_name` attribute may only be applied to a function or static item in an `extern` block.
`rustc` ignores use in other positions but lints against it. This may become an error in the future.
Only the first use of `link_name` on an item has effect.
`rustc` lints against any use following the first with a future-compatibility warning. This may become an error in the future.
The `link_name` attribute may not be used with the [`link_ordinal`] attribute.

External blocks
Attributes on extern blocks
The `link_name` attribute


The Rust Reference › External blocks › Attributes on extern blocks › The `link_ordinal` attribute

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.
`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.
```rust
#[link(name = "exporter", kind = "raw-dylib")]
unsafe extern "stdcall" {
    #[link_ordinal(15)]
    safe fn imported_function_stdcall(i: i32);
}
```
This attribute is only used with the `raw-dylib` linking kind. Using any other kind will result in a compiler error.
Using this attribute with the `link_name` attribute will result in a compiler error.

External blocks
Attributes on extern blocks
The `link_ordinal` attribute


The Rust Reference › External blocks › Attributes on extern blocks › Attributes on function parameters

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

External blocks
Attributes on extern blocks
Attributes on function parameters


The Rust Reference › Generic parameters

```grammar,items
GenericParams -> `<` ( GenericParam (`,` GenericParam)* `,`? )? `>`

GenericParam -> OuterAttribute* ( LifetimeParam | TypeParam | ConstParam )

LifetimeParam -> Lifetime ( `:` LifetimeBounds? )?

TypeParam -> IDENTIFIER ( `:` Bounds? )? ( `=` Type )?

ConstParam ->
    `const` IDENTIFIER `:` Type
    ( `=` ( BlockExpression | IDENTIFIER | `-`?LiteralExpression ) )?
```
[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`.
The order of generic parameters is restricted to lifetime parameters and then type and const parameters intermixed.
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:
```rust
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);
```
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.
[References], [raw pointers], [arrays], [slices], [tuples], and [function pointers] have lifetime or type parameters as well, but are not referred to with path syntax.


The Rust Reference › Generic parameters

`'_` and `'static` are not valid lifetime parameter names.


The Rust Reference › Generic parameters › Const generics

*Const generic parameters* allow items to be generic over constant values.
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.
The only allowed types of const parameters are `u8`, `u16`, `u32`, `u64`, `u128`, `usize`, `i8`, `i16`, `i32`, `i64`, `i128`, `isize`, `char` and `bool`.
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.


The Rust Reference › Generic parameters › Const generics

```rust
// 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];
}
```
```rust,compile_fail
// 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]);
}
```
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.


The Rust Reference › Generic parameters › Const generics

```rust,compile_fail
// 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}]
}
```
A const argument in a [path] specifies the const value to use for that item.
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).
This syntactic restriction is necessary to avoid requiring infinite lookahead when parsing an expression inside of a type.
```rust
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.
```
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].


The Rust Reference › Generic parameters › Const generics

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.
```rust
fn make_buf<const N: usize>() -> [u8; N] {
    [0; _]
    //  ^ Infers `N`.
}
let _: [u8; 1024] = make_buf::<_>();
//                             ^ Infers `1024`.
```
An [inferred const] is not semantically an expression and so is not accepted within braces.
```rust,compile_fail
fn f<const N: usize>() -> [u8; N] { [0; _] }
let _: [_; 1] = f::<{ _ }>();
//                    ^ ERROR `_` not allowed here
```
The inferred const cannot be used in item signatures.
```rust,compile_fail
fn f<const N: usize>(x: [u8; N]) -> [u8; _] { x }
//                                       ^ ERROR not allowed
```
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.


The Rust Reference › Generic parameters › Const generics

```rust,compile_fail
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
```
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]:
```rust,compile_fail
// 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 {}
```
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:
```rust,compile_fail
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
}
```


The Rust Reference › Generic parameters › Where clauses

```grammar,items
WhereClause -> `where` ( WhereClauseItem `,` )* WhereClauseItem?

WhereClauseItem ->
      LifetimeWhereClauseItem
    | TypeBoundWhereClauseItem

LifetimeWhereClauseItem -> Lifetime `:` LifetimeBounds?

TypeBoundWhereClauseItem -> ForLifetimes? Type `:` Bounds?
```
*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.
The `for` keyword can be used to introduce [higher-ranked lifetimes]. It only allows [LifetimeParam] parameters.
```rust
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,
}
```


The Rust Reference › Generic parameters › 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.
```rust,ignore
// 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
}
```


The Rust Reference › Associated items

```grammar,items
AssociatedItem ->
    OuterAttribute* (
        MacroInvocationSemi
      | ( Visibility? ( TypeAlias | ConstantItem | Function ) )
    )
```
*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.
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].
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.
Every associated item kind comes in two varieties: definitions that contain the actual implementation and declarations that declare signatures for definitions.
It is the declarations that make up the contract of traits and what is available on generic types.


The Rust Reference › Associated items › Associated functions and methods

*Associated functions* are [functions] associated with a type.
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 `;`.
The identifier is the name of the function.
The generics, parameter list, return type, and where clause of the associated function must be the same as the associated function declarations's.
An *associated function definition* defines a function associated with another type. It is written the same as a [function item].
A common example is an associated function named `new` that returns a value of the type with which it is associated.
```rust
struct Struct {
    field: i32
}

impl Struct {
    fn new() -> Struct {
        Struct {
            field: 0i32
        }
    }
}

fn main () {
    let _struct = Struct::new();
}
```
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`.
```rust
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);
```

Associated items
Associated functions and methods


The Rust Reference › Associated items › Associated functions and methods › Methods

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.
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):
```text
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.
```rust
// 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) {}
}
```
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`

Associated items
Associated functions and methods
Methods


The Rust Reference › Associated items › Associated functions and methods › Methods › Attributes on method parameters

Lifetimes can be, and usually are, elided with this shorthand.
If the `self` parameter is prefixed with `mut`, it becomes a mutable variable, similar to regular parameters using a `mut` [identifier pattern]. For example:
```rust
trait Changer: Sized {
    fn change(mut self) {}
    fn modify(mut self: Box<Self>) {}
}
```
As an example of methods on a trait, consider the following:
```rust
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.
```rust
struct Circle {
    // ...
}

impl Shape for Circle {
    // ...
}

let circle_shape = Circle::new();
let bounding_box = circle_shape.bounding_box();
```
[!EDITION-2018]
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.
Attributes on method parameters follow the same rules and restrictions as [regular function parameters].

Associated items
Associated functions and methods
Methods
Attributes on method parameters


The Rust Reference › Associated items › Associated types

*Associated types* are [type aliases] associated with another type.
Associated types cannot be defined in [inherent implementations] nor can they be given a default implementation in traits.
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:
```rust,ignore
type Assoc;
type Assoc: Bounds;
type Assoc<Params>;
type Assoc<Params>: Bounds;
type Assoc<Params> where WhereBounds;
type Assoc<Params>: Bounds where WhereBounds;
```
The identifier is the name of the declared type alias.
The optional trait bounds must be fulfilled by the implementations of the type alias.
There is an implicit [`Sized`] bound on associated types that can be relaxed using the special `?Sized` bound.
An *associated type definition* defines a type alias for the implementation of a trait on a type.
They are written similarly to an *associated type declaration*, but cannot contain `Bounds`, but instead must contain a `Type`:
```rust,ignore
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
```
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.
Furthermore, if `Item` is a type parameter, then `Item::Assoc` can be used in type parameters.


The Rust Reference › Associated items › Associated types

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.
```rust
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: