The Rust Reference › Divergence

A *diverging expression* is an expression that never completes normal execution.
```rust
fn diverges() -> ! {
    panic!("This function never returns!");
}

fn example() {
    let x: i32 = diverges(); // This line never completes.
    println!("This is never printed: {x}");
}
```
See the following rules for specific expression divergence behavior:
- [expr.block.diverging] --- Block expressions.
- [expr.if.diverging] --- `if` expressions.
- [expr.loop.block-labels.type] --- Labeled block expressions with `break`.
- [expr.loop.break-value.diverging] --- `loop` expressions with `break`.
- [expr.loop.break.diverging] --- `break` expressions.
- [expr.loop.continue.diverging] --- `continue` expressions.
- [expr.loop.infinite.diverging] --- Infinite `loop` expressions.
- [expr.match.diverging] --- `match` expressions.
- [expr.match.empty] --- Empty `match` expressions.
- [expr.return.diverging] --- `return` expressions.
- [type.never.constraint] --- Function calls returning `!`.
The [`panic!`] macro and related panic-generating macros like [`unreachable!`] also have the type [`!`] and are diverging.
Any expression of type [`!`] is a diverging expression. However, diverging expressions are not limited to type [`!`]; expressions of other types may also diverge (e.g., `Some(loop {})` has type `Option<!>`).
Though `!` is considered an uninhabited type, a type being uninhabited is not sufficient for it to diverge.


The Rust Reference › Divergence

```rust,compile_fail,E0308
enum Empty {}
fn make_never() -> ! {loop{}}
fn make_empty() -> Empty {loop{}}

fn diverging() -> ! {
    // This has a type of `!`.
    // So, the entire function is considered diverging.
    make_never();
    // OK: The type of the body is `!` which matches the return type.
}
fn not_diverging() -> ! {
    // This type is uninhabited.
    // However, the entire function is not considered diverging.
    make_empty();
    // ERROR: The type of the body is `()` but expected type `!`.
}
```
Divergence can propagate to the surrounding block. See [expr.block.diverging].


The Rust Reference › Divergence › Fallback

If a type to be inferred is only unified with diverging expressions, then that type will be inferred to be [`!`].
```rust,compile_fail,E0277
fn foo() -> i32 { 22 }
match foo() {
    // ERROR: The trait bound `!: Default` is not satisfied.
    4 => Default::default(),
    _ => return,
};
```
[!EDITION-2024]
Before the 2024 edition, the type was inferred to instead be `()`.
Importantly, type unification may happen *structurally*, so the fallback `!` may be part of a larger type. The following compiles:
```rust
fn foo() -> i32 { 22 }
// This has the type `Option<!>`, not `!`
match foo() {
    4 => Default::default(),
    _ => Some(return),
};
```


The Rust Reference › Destructors

When an [initialized] [variable] or [temporary] goes out of scope, its *destructor* is run or it is *dropped*. [Assignment] also runs the destructor of its left-hand operand, if it's initialized. If a variable has been partially initialized, only its initialized fields are dropped.
The destructor of a type `T` consists of:
1. If `T: Drop`, calling `<T as core::ops::Drop>::drop`
2. Recursively running the destructor of all of its fields.
    * The fields of a [struct] are dropped in declaration order.
    * The fields of the active [enum variant] are dropped in declaration order.
    * The fields of a [tuple] are dropped in order.
    * The elements of an [array] or owned [slice] are dropped from the first element to the last.
    * The variables that a [closure] captures by move are dropped in an unspecified order.
    * [Trait objects] run the destructor of the underlying type.
    * Other types don't result in any further drops.
If a destructor must be run manually, such as when implementing your own smart pointer, [`core::ptr::drop_in_place`] can be used.
Some examples:


The Rust Reference › Destructors

```rust
struct PrintOnDrop(&'static str);

impl Drop for PrintOnDrop {
    fn drop(&mut self) {
        println!("{}", self.0);
    }
}

let mut overwritten = PrintOnDrop("drops when overwritten");
overwritten = PrintOnDrop("drops when scope ends");

let tuple = (PrintOnDrop("Tuple first"), PrintOnDrop("Tuple second"));

let moved;
// No destructor run on assignment.
moved = PrintOnDrop("Drops when moved");
// Drops now, but is then uninitialized.
moved;

// Uninitialized does not drop.
let uninitialized: PrintOnDrop;

// After a partial move, only the remaining fields are dropped.
let mut partial_move = (PrintOnDrop("first"), PrintOnDrop("forgotten"));
// Perform a partial move, leaving only `partial_move.0` initialized.
core::mem::forget(partial_move.1);
// When partial_move's scope ends, only the first field is dropped.
```


The Rust Reference › Destructors › Drop scopes

Each variable or temporary is associated to a *drop scope*. When control flow leaves a drop scope all variables associated to that scope are dropped in reverse order of declaration (for variables) or creation (for temporaries).
Drop scopes can be determined by replacing [`for`], [`if`], and [`while`] expressions with equivalent expressions using [`match`], [`loop`] and `break`.
Overloaded operators are not distinguished from built-in operators and [binding modes] are not considered.
Given a function, or closure, there are drop scopes for:
* The entire function
* Each [statement]
* Each [expression]
* Each block, including the function body
    * In the case of a [block expression], the scope for the block and the expression are the same scope.
* Each arm of a `match` expression
Drop scopes are nested within one another as follows. When multiple scopes are left at once, such as when returning from a function, variables are dropped from the inside outwards.
* The entire function scope is the outer most scope.
* The function body block is contained within the scope of the entire function.
* The parent of the expression in an expression statement is the scope of the statement.
* The parent of the initializer of a [`let` statement] is the `let` statement's scope.
* The parent of a statement scope is the scope of the block that contains the statement.
* The parent of the expression for a `match` guard is the scope of the arm that the guard is for.
* The parent of the expression after the `=>` in a `match` expression is the scope of the arm that it's in.
* The parent of the arm scope is the scope of the `match` expression that it belongs to.
* The parent of all other scopes is the scope of the immediately enclosing expression.


The Rust Reference › Destructors › Drop scopes › Scopes of function parameters

All function parameters are in the scope of the entire function body, so are dropped last when evaluating the function. Each actual function parameter is dropped after any bindings introduced in that parameter's pattern.
```rust
// Drops `y`, then the second parameter, then `x`, then the first parameter
fn patterns_in_parameters(
    (x, _): (PrintOnDrop, PrintOnDrop),
    (_, y): (PrintOnDrop, PrintOnDrop),
) {}

// drop order is 3 2 0 1
patterns_in_parameters(
    (PrintOnDrop("0"), PrintOnDrop("1")),
    (PrintOnDrop("2"), PrintOnDrop("3")),
);
```

Destructors
Drop scopes
Scopes of function parameters


The Rust Reference › Destructors › Drop scopes › Scopes of local variables

Local variables declared in a `let` statement are associated to the scope of the block that contains the `let` statement.
```rust
let declared_first = PrintOnDrop("Dropped last in outer scope");
{
    let declared_in_block = PrintOnDrop("Dropped in inner scope");
}
let declared_last = PrintOnDrop("Dropped first in outer scope");
```
Local variables declared in a `match` expression or pattern-matching `match` guard are associated to the arm scope of the `match` arm that they are declared in.

Destructors
Drop scopes
Scopes of local variables


The Rust Reference › Destructors › Drop scopes › Scopes of local variables

```rust
match PrintOnDrop("Dropped last in the first arm's scope") {
    // When guard evaluation succeeds, control-flow stays in the arm and
    // values may be moved from the scrutinee into the arm's bindings,
    // causing them to be dropped in the arm's scope.
    x if let y = PrintOnDrop("Dropped second in the first arm's scope")
        && let z = PrintOnDrop("Dropped first in the first arm's scope") =>
    {
        let declared_in_block = PrintOnDrop("Dropped in inner scope");
        // Pattern-matching guards' bindings and temporaries are dropped in
        // reverse order, dropping each guard condition operand's bindings
        // before its temporaries. Lastly, variables bound by the arm's
        // pattern are dropped.
    }
    _ => unreachable!(),
}

match PrintOnDrop("Dropped in the enclosing temporary scope") {
    // When guard evaluation fails, control-flow leaves the arm scope,
    // causing bindings and temporaries from earlier pattern-matching
    // guard condition operands to be dropped. This occurs before evaluating
    // the next arm's guard or body.
    _ if let y = PrintOnDrop("Dropped in the first arm's scope")
        && false => unreachable!(),
    // When a guard is executed multiple times due to self-overlapping
    // or-patterns, control-flow leaves the arm scope when the guard fails
    // and re-enters the arm scope before executing the guard again.
    _ | _ if let y = PrintOnDrop("Dropped in the second arm's scope twice")
        && false => unreachable!(),
    _ => {},
}
```
Variables in patterns are dropped in reverse order of declaration within the pattern.
```rust
let (declared_first, declared_last) = (
    PrintOnDrop("Dropped last"),
    PrintOnDrop("Dropped first"),
);
```


The Rust Reference › Destructors › Drop scopes › Scopes of local variables

For the purpose of drop order, [or-patterns] declare bindings in the order given by the first subpattern.
```rust
// Drops `x` before `y`.
fn or_pattern_drop_order<T>(
    (Ok([x, y]) | Err([y, x])): Result<[T; 2], [T; 2]>
//   ^^^^^^^^^^   ^^^^^^^^^^^ This is the second subpattern.
//   |
//   This is the first subpattern.
//
//   In the first subpattern, `x` is declared before `y`. Since it is
//   the first subpattern, that is the order used even if the second
//   subpattern, where the bindings are declared in the opposite
//   order, is matched.
) {}

// Here we match the first subpattern, and the drops happen according
// to the declaration order in the first subpattern.
or_pattern_drop_order(Ok([
    PrintOnDrop("Declared first, dropped last"),
    PrintOnDrop("Declared last, dropped first"),
]));

// Here we match the second subpattern, and the drops still happen
// according to the declaration order in the first subpattern.
or_pattern_drop_order(Err([
    PrintOnDrop("Declared last, dropped first"),
    PrintOnDrop("Declared first, dropped last"),
]));
```


The Rust Reference › Destructors › Drop scopes › Temporary scopes

The *temporary scope* of an expression is the scope that is used for the temporary variable that holds the result of that expression when used in a [place context], unless it is [promoted].
Apart from lifetime extension, the temporary scope of an expression is the smallest scope that contains the expression and is one of the following:
* The entire function.
* A statement.
* The body of an [`if`], [`while`] or [`loop`] expression.
* The `else` block of an `if` expression.
* The non-pattern matching condition expression of an `if` or `while` expression or a non-pattern-matching `match` [guard condition operand].
* The pattern-matching guard, if present, and body expression for a `match` arm.
* Each operand of a [lazy boolean expression].
* The pattern-matching condition(s) and consequent body of [`if`] ([destructors.scope.temporary.edition2024]).
* The pattern-matching condition and loop body of [`while`].
* The entirety of the tail expression of a block ([destructors.scope.temporary.edition2024]).
The [scrutinee] of a `match` expression is not a temporary scope, so temporaries in the scrutinee can be dropped after the `match` expression. For example, the temporary for `1` in `match 1 { ref mut z => z };` lives until the end of the statement.
The desugaring of a [destructuring assignment] restricts the temporary scope of its assigned value operand (the RHS). For details, see [expr.assign.destructure.tmp-scopes].
[!EDITION-2024]
The 2024 edition added two new temporary scope narrowing rules: `if let` temporaries are dropped before the `else` block, and temporaries of tail expressions of blocks are dropped immediately after the tail expression is evaluated.
Some examples:

Destructors
Drop scopes
Temporary scopes


The Rust Reference › Destructors › Drop scopes › Temporary scopes

```rust
let local_var = PrintOnDrop("local var");

// Dropped once the condition has been evaluated
if PrintOnDrop("If condition").0 == "If condition" {
    // Dropped at the end of the block
    PrintOnDrop("If body").0
} else {
    unreachable!()
};

if let "if let scrutinee" = PrintOnDrop("if let scrutinee").0 {
    PrintOnDrop("if let consequent").0
    // `if let consequent` dropped here
}
// `if let scrutinee` is dropped here
else {
    PrintOnDrop("if let else").0
    // `if let else` dropped here
};

while let x = PrintOnDrop("while let scrutinee").0 {
    PrintOnDrop("while let loop body").0;
    break;
    // `while let loop body` dropped here.
    // `while let scrutinee` dropped here.
}

// Dropped before the first ||
(PrintOnDrop("first operand").0 == ""
// Dropped before the )
|| PrintOnDrop("second operand").0 == "")
// Dropped before the ;
|| PrintOnDrop("third operand").0 == "";

// Scrutinee is dropped at the end of the function, before local variables
// (because this is the tail expression of the function body block).
match PrintOnDrop("Matched value in final expression") {
    // Non-pattern-matching guards' temporaries are dropped once the
    // condition has been evaluated
    _ if PrintOnDrop("guard condition").0 == "" => (),
    // Pattern-matching guards' temporaries are dropped when leaving the
    // arm's scope
    _ if let "guard scrutinee" = PrintOnDrop("guard scrutinee").0 => {
        let _ = &PrintOnDrop("lifetime-extended temporary in inner scope");
        // `lifetime-extended temporary in inner scope` is dropped here
    }
    // `guard scrutinee` is dropped here
    _ => (),
}
```


The Rust Reference › Destructors › Drop scopes › Operands

Temporaries are also created to hold the result of operands to an expression while the other operands are evaluated. The temporaries are associated to the scope of the expression with that operand. Since the temporaries are moved from once the expression is evaluated, dropping them has no effect unless one of the operands to an expression breaks out of the expression, returns, or panics.
```rust
loop {
    // Tuple expression doesn't finish evaluating so operands drop in reverse order
    (
        PrintOnDrop("Outer tuple first"),
        PrintOnDrop("Outer tuple second"),
        (
            PrintOnDrop("Inner tuple first"),
            PrintOnDrop("Inner tuple second"),
            break,
        ),
        PrintOnDrop("Never created"),
    );
}
```


The Rust Reference › Destructors › Drop scopes › Constant promotion

Promotion of a value expression to a `'static` slot occurs when the expression could be written in a constant and borrowed, and that borrow could be dereferenced where the expression was originally written, without changing the runtime behavior. That is, the promoted expression can be evaluated at compile-time and the resulting value does not contain [interior mutability] or [destructors] (these properties are determined based on the value where possible, e.g. `&None` always has the type `&'static Option<_>`, as it contains nothing disallowed).

Destructors
Drop scopes
Constant promotion


The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Extending based on patterns

The exact rules for temporary lifetime extension are subject to change. This is describing the current behavior only.
The temporary scopes for expressions in `let` statements are sometimes *extended* to the scope of the block containing the `let` statement. This is done when the usual temporary scope would be too small, based on certain syntactic rules. For example:
```rust
let x = &mut 0;
// Usually a temporary would be dropped by now, but the temporary for `0` lives
// to the end of the block.
println!("{}", x);
```
Lifetime extension also applies to `static` and `const` items, where it makes temporaries live until the end of the program. For example:
```rust
const C: &Vec<i32> = &Vec::new();
// Usually this would be a dangling reference as the `Vec` would only
// exist inside the initializer expression of `C`, but instead the
// borrow gets lifetime-extended so it effectively has `'static` lifetime.
println!("{:?}", C);
```
If a [borrow], dereference, field, or [tuple indexing expression] has an extended temporary scope, then so does its operand. If an [indexing expression] has an extended temporary scope, then the indexed expression also has an extended temporary scope.
An *extending pattern* is either:
* An [identifier pattern] that binds by reference or mutable reference.
```rust
  # fn temp() {}
  let ref x = temp(); // Binds by reference.
  # x;
  let ref mut x = temp(); // Binds by mutable reference.
  # x;
```
* A struct, tuple, tuple struct, slice, or or-pattern where at least one of the direct subpatterns is an extending pattern.

Destructors
Drop scopes
Temporary lifetime extension
Extending based on patterns


The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Extending based on expressions

```rust
  # use core::sync::atomic::{AtomicU64, Ordering::Relaxed};
  # static X: AtomicU64 = AtomicU64::new(0);
  struct W<T>(T);
  # impl<T> Drop for W<T> { fn drop(&mut self) { X.fetch_add(1, Relaxed); } }
  let W { 0: ref x } = W(()); // Struct pattern.
  # x;
  let W(ref x) = W(()); // Tuple struct pattern.
  # x;
  let (W(ref x),) = (W(()),); // Tuple pattern.
  # x;
  let [W(ref x), ..] = [W(())]; // Slice pattern.
  # x;
  let (Ok(W(ref x)) | Err(&ref x)) = Ok(W(())); // Or pattern.
  # x;
  //
  // All of the temporaries above are still live here.
  # assert_eq!(0, X.load(Relaxed));
```
So `ref x`, `V(ref x)` and `[ref x, y]` are all extending patterns, but `x`, `&ref x` and `&(ref x,)` are not.
If the pattern in a `let` statement is an extending pattern then the temporary scope of the initializer expression is extended.
```rust
// This is an extending pattern, so the temporary scope is extended.
let ref x = *&temp(); // OK
```
```rust,compile_fail,E0716
// This is neither an extending pattern nor an extending expression,
// so the temporary is dropped at the semicolon.
let &ref x = *&&temp(); // ERROR
```
```rust
// This is not an extending pattern but it is an extending expression,
// so the temporary lives beyond the `let` statement.
let &ref x = &*&temp(); // OK
```

Destructors
Drop scopes
Temporary lifetime extension
Extending based on expressions


The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples

For a let statement with an initializer, an *extending expression* is an expression which is one of the following:
* The initializer expression.
* The operand of an extending [borrow] expression.
* The [super operands] of an extending [super macro call] expression.
* The operand(s) of an extending array, cast, braced struct, or tuple expression.
* The arguments to an extending [tuple struct] or [tuple enum variant] constructor expression.
* The final expression of an extending [block expression] except for an [async block expression].
* The final expression of an extending [`if`] expression's consequent, `else if`, or `else` block.
* An arm expression of an extending [`match`] expression.
The desugaring of a [destructuring assignment] makes its assigned value operand (the RHS) an extending expression within a newly-introduced block. For details, see [expr.assign.destructure.tmp-ext].
So the borrow expressions in `&mut 0`, `(&1, &mut 2)`, and `Some(&mut 3)` are all extending expressions. The borrows in `&0 + &1` and `f(&mut 0)` are not.
The operand of an extending [borrow] expression has its [temporary scope] [extended].
The [super temporaries] of an extending [super macro call] expression have their scopes [extended].
`rustc` does not treat [array repeat operands] of extending [array] expressions as extending expressions. Whether it should is an open question.
For details, see Rust issue #146092.
Here are some examples where expressions have extended temporary scopes:

Destructors
Drop scopes
Temporary lifetime extension
Examples


The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples

```rust,edition2024
let x = &temp(); // Operand of borrow.
let x = &raw const *&temp(); // Operand of raw borrow.
let x = &temp() as &dyn Send; // Operand of cast.
let x = (&*&temp(),); // Operand of tuple constructor.
struct W<T>(T);
let x = W(&temp()); // Argument to tuple struct constructor.
let x = Some(&temp()); // Argument to tuple enum variant constructor.
let x = { [Some(&temp())] }; // Final expr of block.
let x = const { &temp() }; // Final expr of `const` block.
let x = unsafe { &temp() }; // Final expr of `unsafe` block.
let x = if true { &temp() } else { &temp() };
//              ^^^^^^^^^^^^^^^^^^^^^^^^^^^^
//           Final exprs of `if`/`else` blocks.
let x = match () { _ => &temp() }; // `match` arm expression.
let x = pin!(temp()); // Super operand of super macro call expression.
let x = pin!({ &mut temp() }); // As above.
let x = format_args!("{:?}", temp()); // As above.
//
// All of the temporaries above are still live here.
```
Here are some examples where expressions don't have extended temporary scopes:
```rust,compile_fail,E0716
// Arguments to function calls are not extending expressions. The
// temporary is dropped at the semicolon.
let x = core::convert::identity(&temp()); // ERROR
```
```rust,compile_fail,E0716
// Receivers of method calls are not extending expressions.
let x = (&temp()).use_temp(); // ERROR
```
```rust,compile_fail,E0716
// Scrutinees of match expressions are not extending expressions.
let x = match &temp() { x => x }; // ERROR
```


The Rust Reference › Destructors › Drop scopes › Temporary lifetime extension › Examples

```rust,compile_fail,E0515
// Final expressions of `async` blocks are not extending expressions.
let x = async { &temp() }; // ERROR
```
```rust,compile_fail,E0515
// Final expressions of closures are not extending expressions.
let x = || &temp(); // ERROR
```
```rust,compile_fail,E0716
// Operands of loop breaks are not extending expressions.
let x = loop { break &temp() }; // ERROR
```
```rust,compile_fail,E0716
// Operands of breaks to labels are not extending expressions.
let x = 'a: { break 'a &temp() }; // ERROR
```
```rust,edition2024,compile_fail,E0716
// The argument to `pin!` is only an extending expression if the call
// is an extending expression. Since it's not, the inner block is not
// an extending expression, so the temporaries in its trailing
// expression are dropped immediately.
pin!({ &temp() }); // ERROR
```
```rust,edition2024,compile_fail,E0716
// As above.
format_args!("{:?}", { &temp() }); // ERROR
```


The Rust Reference › Destructors › Not running destructors › Manually suppressing destructors

[`core::mem::forget`] can be used to prevent the destructor of a variable from being run, and [`core::mem::ManuallyDrop`] provides a wrapper to prevent a variable or field from being dropped automatically.
Preventing a destructor from being run via [`core::mem::forget`] or other means is safe even if it has a type that isn't `'static`. Besides the places where destructors are guaranteed to run as defined by this document, types may *not* safely rely on a destructor being run for soundness.

Destructors
Not running destructors
Manually suppressing destructors


The Rust Reference › Destructors › Not running destructors › Process termination without unwinding

There are some ways to terminate the process without [unwinding], in which case destructors will not be run.
The standard library provides [`std::process::exit`] and [`std::process::abort`] to do this explicitly. Additionally, if the panic handler is set to `abort`, panicking will always terminate the process without destructors being run.
There is one additional case to be aware of: when a panic reaches a [non-unwinding ABI boundary], either no destructors will run, or all destructors up until the ABI boundary will run.

Destructors
Not running destructors
Process termination without unwinding


The Rust Reference › Lifetime elision

Rust has rules that allow lifetimes to be elided in various places where the compiler can infer a sensible default choice.


The Rust Reference › Lifetime elision › Lifetime elision in functions

In order to make common patterns more ergonomic, lifetime arguments can be *elided* in [function item], [function pointer], and [closure trait] signatures. The following rules are used to infer lifetime parameters for elided lifetimes.
It is an error to elide lifetime parameters that cannot be inferred.
The placeholder lifetime, `'_`, can also be used to have a lifetime inferred in the same way. For lifetimes in paths, using `'_` is preferred.
Trait object lifetimes follow different rules discussed below.
* Each elided lifetime in the parameters becomes a distinct lifetime parameter.
* If there is exactly one lifetime used in the parameters (elided or not), that lifetime is assigned to *all* elided output lifetimes.
In method signatures there is another rule
* If the receiver has type `&Self`  or `&mut Self`, then the lifetime of that reference to `Self` is assigned to all elided output lifetime parameters.
Examples:

Lifetime elision
Lifetime elision in functions


The Rust Reference › Lifetime elision › Lifetime elision in functions

```rust
fn print1(s: &str);                                   // elided
fn print2(s: &'_ str);                                // also elided
fn print3<'a>(s: &'a str);                            // expanded

fn debug1(lvl: usize, s: &str);                       // elided
fn debug2<'a>(lvl: usize, s: &'a str);                // expanded

fn substr1(s: &str, until: usize) -> &str;            // elided
fn substr2<'a>(s: &'a str, until: usize) -> &'a str;  // expanded

fn get_mut1(&mut self) -> &mut dyn T;                 // elided
fn get_mut2<'a>(&'a mut self) -> &'a mut dyn T;       // expanded

fn args1<T: ToCStr>(&mut self, args: &[T]) -> &mut Command;                  // elided
fn args2<'a, 'b, T: ToCStr>(&'a mut self, args: &'b [T]) -> &'a mut Command; // expanded

fn other_args1<'a>(arg: &str) -> &'a str;             // elided
fn other_args2<'a, 'b>(arg: &'b str) -> &'a str;      // expanded

fn new1(buf: &mut [u8]) -> Thing<'_>;                 // elided - preferred
fn new2(buf: &mut [u8]) -> Thing;                     // elided
fn new3<'a>(buf: &'a mut [u8]) -> Thing<'a>;          // expanded

type FunPtr1 = fn(&str) -> &str;                      // elided
type FunPtr2 = for<'a> fn(&'a str) -> &'a str;        // expanded

type FunTrait1 = dyn Fn(&str) -> &str;                // elided
type FunTrait2 = dyn for<'a> Fn(&'a str) -> &'a str;  // expanded
```


The Rust Reference › Lifetime elision › Lifetime elision in functions

```rust,compile_fail
// The following examples show situations where it is not allowed to elide the
// lifetime parameter.

// Cannot infer, because there are no parameters to infer from.
fn get_str() -> &str;                                 // ILLEGAL

// Cannot infer, ambiguous if it is borrowed from the first or second parameter.
fn frob(s: &str, t: &str) -> &str;                    // ILLEGAL
```


The Rust Reference › Lifetime elision › Default trait object lifetimes

The assumed lifetime of references held by a [trait object] is called its _default object lifetime bound_. These were defined in [RFC 599] and amended in [RFC 1156].
These default object lifetime bounds are used instead of the lifetime parameter elision rules defined above when the lifetime bound is omitted entirely.
If `'_` is used as the lifetime bound then the bound follows the usual elision rules.
If the trait object is used as a type argument of a generic type then the containing type is first used to try to infer a bound.
* If there is a unique bound from the containing type then that is the default.
* If there is more than one bound from the containing type then an explicit bound must be specified.
If neither of those rules apply, then the bounds on the trait are used:
* If the trait is defined with a single lifetime _bound_ then that bound is used.
* If `'static` is used for any lifetime bound then `'static` is used.
* If the trait has no lifetime bounds, then the lifetime is inferred in expressions and is `'static` outside of expressions.

Lifetime elision
Default trait object lifetimes


The Rust Reference › Lifetime elision › Default trait object lifetimes

```rust
// For the following trait...
trait Foo { }

// These two are the same because Box<T> has no lifetime bound on T
type T1 = Box<dyn Foo>;
type T2 = Box<dyn Foo + 'static>;

// ...and so are these:
impl dyn Foo {}
impl dyn Foo + 'static {}

// ...so are these, because &'a T requires T: 'a
type T3<'a> = &'a dyn Foo;
type T4<'a> = &'a (dyn Foo + 'a);

// std::cell::Ref<'a, T> also requires T: 'a, so these are the same
type T5<'a> = std::cell::Ref<'a, dyn Foo>;
type T6<'a> = std::cell::Ref<'a, dyn Foo + 'a>;
```
```rust,compile_fail
// This is an example of an error.
struct TwoBounds<'a, 'b, T: ?Sized + 'a + 'b> {
    f1: &'a i32,
    f2: &'b i32,
    f3: T,
}
type T7<'a, 'b> = TwoBounds<'a, 'b, dyn Foo>;
//                                  ^^^^^^^
// Error: the lifetime bound for this object type cannot be deduced from context
```
Note that the innermost object sets the bound, so `&'a Box<dyn Foo>` is still `&'a Box<dyn Foo + 'static>`.
```rust
// For the following trait...
trait Bar<'a>: 'a { }

// ...these two are the same:
type T1<'a> = Box<dyn Bar<'a>>;
type T2<'a> = Box<dyn Bar<'a> + 'a>;

// ...and so are these:
impl<'a> dyn Bar<'a> {}
impl<'a> dyn Bar<'a> + 'a {}
```


The Rust Reference › Lifetime elision › `const` and `static` elision

Both [constant] and [static] declarations of reference types have *implicit* `'static` lifetimes unless an explicit lifetime is specified. As such, the constant declarations involving `'static` above may be written without the lifetimes.
```rust
// STRING: &'static str
const STRING: &str = "bitstring";

struct BitsNStrings<'a> {
    mybits: [u32; 2],
    mystring: &'a str,
}

// BITS_N_STRINGS: BitsNStrings<'static>
const BITS_N_STRINGS: BitsNStrings<'_> = BitsNStrings {
    mybits: [1, 2],
    mystring: STRING,
};
```
Note that if the `static` or `const` items include function or closure references, which themselves include references, the compiler will first try the standard elision rules. If it is unable to resolve the lifetimes by its usual rules, then it will error. By way of example:
```rust
// Resolved as `for<'a> fn(&'a str) -> &'a str`.
const RESOLVED_SINGLE: fn(&str) -> &str = |x| x;

// Resolved as `for<'a, 'b, 'c> Fn(&'a Foo, &'b Bar, &'c Baz) -> usize`.
const RESOLVED_MULTIPLE: &dyn Fn(&Foo, &Bar, &Baz) -> usize = &somefunc;
```
```rust,compile_fail
// There is insufficient information to bound the return reference lifetime
// relative to the argument lifetimes, so this is an error.
const RESOLVED_STATIC: &dyn Fn(&Foo, &Bar) -> &Baz = &somefunc;
//                                            ^
// this function's return type contains a borrowed value, but the signature
// does not say whether it is borrowed from argument 1 or argument 2
```

Lifetime elision
`const` and `static` elision


The Rust Reference › Special types and traits

Certain types and traits that exist in [the standard library] are known to the Rust compiler. This chapter documents the special features of these types and traits.


The Rust Reference › Special types and traits › `Box<T>`

[`Box<T>`] has a few special features that Rust doesn't currently allow for user defined types.
* The [dereference operator] for `Box<T>` produces a place which can be [moved from]. This means that the `*` operator and the destructor of `Box<T>` are built-in to the language.
* [Methods] can take `Box<Self>` as a receiver.
* A trait may be implemented for `Box<T>` in the same crate as `T`, which the [orphan rules] prevent for other generic types.


The Rust Reference › Special types and traits › `Rc<T>`

[Methods] can take [`Rc<Self>`] as a receiver.


The Rust Reference › Special types and traits › `Arc<T>`

[Methods] can take [`Arc<Self>`] as a receiver.


The Rust Reference › Special types and traits › `Pin<P>`

[Methods] can take [`Pin<P>`] as a receiver.


The Rust Reference › Special types and traits › `UnsafeCell<T>`

[`std::cell::UnsafeCell<T>`] is used for [interior mutability]. It ensures that the compiler doesn't perform optimisations that are incorrect for such types.
It also ensures that [`static` items] which have a type with interior mutability aren't placed in memory marked as read only.

Special types and traits
`UnsafeCell<T>`


The Rust Reference › Special types and traits › `PhantomData<T>`

[`std::marker::PhantomData<T>`] is a [zero-sized], minimum alignment, type that is considered to own a `T` for the purposes of [variance], [drop check], and auto traits.

Special types and traits
`PhantomData<T>`


The Rust Reference › Special types and traits › Operator traits

The traits in [`std::ops`] and [`std::cmp`] are used to overload [operators], [indexing expressions], and [call expressions].

Special types and traits
Operator traits


The Rust Reference › Special types and traits › `Deref` and `DerefMut`

As well as overloading the unary `*` operator, [`Deref`] and [`DerefMut`] are also used in [method resolution] and [deref coercions].

Special types and traits
`Deref` and `DerefMut`


The Rust Reference › Special types and traits › `Drop`

The [`Drop`] trait provides a [destructor], to be run whenever a value of this type is to be destroyed.


The Rust Reference › Special types and traits › `Copy`

The [`Copy`] trait changes the semantics of a type implementing it.
Values whose type implements `Copy` are copied rather than moved upon assignment.
`Copy` can only be implemented for types which do not implement `Drop`, and whose fields are all `Copy`. For enums, this means all fields of all variants have to be `Copy`. For unions, this means all variants have to be `Copy`.
`Copy` is implemented by the compiler for
* [Tuples] of `Copy` types
* [Function pointers]
* [Function items]
* [Closures] that capture no values or that only capture values of `Copy` types


The Rust Reference › Special types and traits › `Clone`

The [`Clone`] trait is a supertrait of `Copy`, so it also needs compiler generated implementations.
It is implemented by the compiler for the following types:
* Types with a built-in `Copy` implementation (see above)
* [Tuples] of `Clone` types
* [Closures] that only capture values of `Clone` types or capture no values from the environment


The Rust Reference › Special types and traits › `Send`

The [`Send`] trait indicates that a value of this type is safe to send from one thread to another.


The Rust Reference › Special types and traits › `Sync`

The [`Sync`] trait indicates that a value of this type is safe to share between multiple threads.
This trait must be implemented for all types used in immutable [`static` items].


The Rust Reference › Special types and traits › `Termination`

The [`Termination`] trait indicates the acceptable return types for the [main function] and [test functions].


The Rust Reference › Special types and traits › Auto traits

The [`Send`], [`Sync`], [`Unpin`], [`UnwindSafe`], and [`RefUnwindSafe`] traits are _auto traits_. Auto traits have special properties.
If no explicit implementation or negative implementation is written out for an auto trait for a given type, then the compiler implements it automatically according to the following rules:
* `&T`, `&mut T`, `*const T`, `*mut T`, `[T; n]`, and `[T]` implement the trait if `T` does.
* Function item types and function pointers automatically implement the trait.
* Structs, enums, unions, and tuples implement the trait if all of their fields do.
* Closures implement the trait if the types of all of their captures do. A closure that captures a `T` by shared reference and a `U` by value implements any auto traits that both `&T` and `U` do.
For generic types (counting the built-in types above as generic over `T`), if a generic implementation is available, then the compiler does not automatically implement it for types that could use the implementation except that they do not meet the requisite trait bounds. For instance, the standard library implements `Send` for all `&T` where `T` is `Sync`; this means that the compiler will not implement `Send` for `&T` if `T` is `Send` but not `Sync`.
Auto traits can also have negative implementations, shown as `impl !AutoTrait for T` in the standard library documentation, that override the automatic implementations. For example `*mut T` has a negative implementation of `Send`, and so `*mut T` is not `Send`, even if `T` is. There is currently no stable way to specify additional negative implementations; they exist only in the standard library.


The Rust Reference › Special types and traits › Auto traits

Auto traits may be added as an additional bound to any [trait object], even though normally only one trait is allowed. For instance, `Box<dyn Debug + Send + UnwindSafe>` is a valid type.


The Rust Reference › Special types and traits › `Sized`

The [`Sized`] trait indicates that the size of this type is known at compile-time; that is, it's not a [dynamically sized type].
[Type parameters] (except `Self` in traits) are `Sized` by default, as are [associated types].
`Sized` is always implemented automatically by the compiler, not by [implementation items].
These implicit `Sized` bounds may be relaxed by using the special `?Sized` bound.


The Rust Reference › Names

An *entity* is a language construct that can be referred to in some way within the source program, usually via a [path]. Entities include [types], [items], [generic parameters], [variable bindings], [loop labels], [lifetimes], [fields], [attributes], and [lints].
A *declaration* is a syntactical construct that can introduce a *name* to refer to an entity. Entity names are valid within a [*scope*] --- a region of source text where that name may be referenced.
Some entities are explicitly declared in the source code, and some are implicitly declared as part of the language or compiler extensions.
[*Paths*] are used to refer to an entity, possibly in another module or type.
Lifetimes and loop labels use a dedicated syntax using a leading quote.
Names are segregated into different [*namespaces*], allowing entities in different namespaces to share the same name without conflict.
[*Name resolution*] is the compile-time process of tying paths, identifiers, and labels to entity declarations.
Access to certain names may be restricted based on their [*visibility*].


The Rust Reference › Names › Explicitly declared entities

Entities that explicitly introduce a name in the source code are:
* [Items]:
    * [Module declarations]
    * [External crate declarations]
    * [Use declarations]
    * [Function declarations] and [function parameters]
    * [Type aliases]
    * [struct], [union], [enum], enum variant declarations, and their named fields
    * [Constant item declarations]
    * [Static item declarations]
    * [Trait item declarations] and their [associated items]
    * [External block items]
    * [`macro_rules` declarations] and [matcher metavariables]
    * [Implementation] associated items
* [Expressions]:
    * [Closure] parameters
    * [`while let`] pattern bindings
    * [`for`] pattern bindings
    * [`if let`] pattern bindings
    * [`match`] pattern bindings
    * [Loop labels]
* [Generic parameters]
* [Higher ranked trait bounds]
* [`let` statement] pattern bindings
* The [`macro_use` attribute] can introduce macro names from another crate
* The [`macro_export` attribute] can introduce an alias for the macro into the crate root
Additionally, [macro invocations] and [attributes] can introduce names by expanding to one of the above items.


The Rust Reference › Names › Implicitly declared entities

The following entities are implicitly defined by the language, or are introduced by compiler options and extensions:
* [Language prelude]:
    * [Boolean type] --- `bool`
    * Textual types --- [`char`] and [`str`]
    * [Integer types] --- `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
    * [Machine-dependent integer types] --- `usize` and `isize`
    * [floating-point types] --- `f32` and `f64`
* [Built-in attributes]
* [Standard library prelude] items, attributes, and macros
* Standard library crates in the root module
* External crates linked by the compiler
* [Tool attributes]
* [Lints] and [tool lint attributes]
* [Derive helper attributes] are valid within an item without being explicitly imported
* The [`'static`] lifetime
Additionally, the crate root module does not have a name, but can be referred to with certain [path qualifiers] or aliases.


The Rust Reference › Namespaces

A *namespace* is a logical grouping of declared [names]. Names are segregated into separate namespaces based on the kind of entity the name refers to. Namespaces allow the occurrence of a name in one namespace to not conflict with the same name in another namespace.
There are several different namespaces that each contain different kinds of entities. The use of a name will look for the declaration of that name in different namespaces, based on the context, as described in the [name resolution] chapter.
The following is a list of namespaces, with their corresponding entities:
* Type Namespace
    * [Module declarations]
    * [External crate declarations]
    * [External crate prelude] items
    * [Struct], [union], [enum], enum variant declarations
    * [Trait item declarations]
    * [Type aliases]
    * [Associated type declarations]
    * Built-in types: [boolean], [numeric], [`char`], and [`str`]
    * [Generic type parameters]
    * [`Self` type]
    * [Tool attribute modules]
* Value Namespace
    * [Function declarations]
    * [Constant item declarations]
    * [Static item declarations]
    * [Struct constructors]
    * [Enum variant constructors]
    * [`Self` constructors]
    * [Generic const parameters]
    * [Associated const declarations]
    * [Associated function declarations]
    * Local bindings --- [`let`], [`if let`], [`while let`], [`for`], [`match`] arms, [function parameters], [closure parameters]
    * Captured [closure] variables
* Macro Namespace
    * [`macro_rules` declarations]
    * [Built-in attributes]
    * [Tool attributes]
    * [Function-like procedural macros]
    * [Derive macros]
    * [Derive macro helpers]
    * [Attribute macros]
* Lifetime Namespace
    * [Generic lifetime parameters]
* Label Namespace
    * [Loop labels]
    * [Block labels]


The Rust Reference › Namespaces

An example of how overlapping names in different namespaces can be used unambiguously:
```rust
// Foo introduces a type in the type namespace and a constructor in the value
// namespace.
struct Foo(u32);

// The `Foo` macro is declared in the macro namespace.
macro_rules! Foo {
    () => {};
}

// `Foo` in the `f` parameter type refers to `Foo` in the type namespace.
// `'Foo` introduces a new lifetime in the lifetime namespace.
fn example<'Foo>(f: Foo) {
    // `Foo` refers to the `Foo` constructor in the value namespace.
    let ctor = Foo;
    // `Foo` refers to the `Foo` macro in the macro namespace.
    Foo!{}
    // `'Foo` introduces a label in the label namespace.
    'Foo: loop {
        // `'Foo` refers to the `'Foo` lifetime parameter, and `Foo`
        // refers to the type namespace.
        let x: &'Foo Foo;
        // `'Foo` refers to the label.
        break 'Foo;
    }
}
```


The Rust Reference › Namespaces › Named entities without a namespace

The following entities have explicit names, but the names are not a part of any specific namespace.

Namespaces
Named entities without a namespace


The Rust Reference › Namespaces › Named entities without a namespace › Fields

Even though struct, enum, and union fields are named, the named fields do not live in an explicit namespace. They can only be accessed via a [field expression], which only inspects the field names of the specific type being accessed.

Namespaces
Named entities without a namespace
Fields


The Rust Reference › Namespaces › Named entities without a namespace › Use declarations

A [use declaration] has named aliases that it imports into scope, but the `use` item itself does not belong to a specific namespace. Instead, it can introduce aliases into multiple namespaces, depending on the item kind being imported.

Namespaces
Named entities without a namespace
Use declarations


The Rust Reference › Namespaces › Sub-namespaces

The macro namespace is split into two sub-namespaces: one for [bang-style macros] and one for [attributes]. When an attribute is resolved, any bang-style macros in scope will be ignored. And conversely resolving a bang-style macro will ignore attribute macros in scope. This prevents one style from shadowing another.
For example, the [`cfg` attribute] and the [`cfg` macro] are two different entities with the same name in the macro namespace, but they can still be used in their respective context.
`use` imports still cannot create duplicate bindings of the same name in a module or block, regardless of sub-namespace.
```rust,ignore
#[macro_export]
macro_rules! mymac {
    () => {};
}

use myattr::mymac; // error[E0252]: the name `mymac` is defined multiple times.
```


The Rust Reference › Scopes

A *scope* is the region of source text where a named [entity] may be referenced with that name. The following sections provide details on the scoping rules and behavior, which depend on the kind of entity and where it is declared. The process of how names are resolved to entities is described in the [name resolution] chapter. More information on "drop scopes" used for the purpose of running destructors may be found in the [destructors] chapter.


The Rust Reference › Scopes › Item scopes

The name of an item declared directly in a [module] has a scope that extends from the start of the module to the end of the module. These items are also members of the module and can be referred to with a [path] leading from their module.
The name of an item declared as a [statement] has a scope that extends from the start of the block the item statement is in until the end of the block.
It is an error to introduce an item with a duplicate name of another item in the same [namespace] within the same module or block. [Asterisk glob imports] have special behavior for dealing with duplicate names and shadowing, see the linked chapter for more details.
Items in a module may shadow items in a prelude.
Item names from outer modules are not in scope within a nested module. A [path] may be used to refer to an item in another module.


The Rust Reference › Scopes › Item scopes › Associated item scopes

[Associated items] are not scoped and can only be referred to by using a [path] leading from the type or trait they are associated with. [Methods] can also be referred to via [call expressions].
Similar to items within a module or block,  it is an error to introduce an item within a trait or implementation that is a duplicate of another item in the trait or impl in the same namespace.

Scopes
Item scopes
Associated item scopes


The Rust Reference › Scopes › Pattern binding scopes

The scope of a local variable [pattern] binding depends on where it is used:
* [`let` statement] bindings range from just after the `let` statement until the end of the block where it is declared.
* [Function parameter] bindings are within the body of the function.
* [Closure parameter] bindings are within the closure body.
* [`for`] bindings are within the loop body.
* [`if let`] and [`while let`] bindings are valid in the following conditions as well as the consequent block.
* [`match` arms] bindings are within the [match guard] and the match arm expression.
* [`match` guard `let`] bindings are valid in the following guard conditions and the match arm expression.
Local variable scopes do not extend into item declarations.


The Rust Reference › Scopes › Pattern binding scopes › Pattern binding shadowing

Pattern bindings are allowed to shadow any name in scope with the following exceptions which are an error:
* [Const generic parameters]
* [Static items]
* [Const items]
* Constructors for [structs] and [enums]
The following example illustrates how local bindings can shadow item declarations:
```rust
fn shadow_example() {
    // Since there are no local variables in scope yet, this resolves to the function.
    foo(); // prints `function`
    let foo = || println!("closure");
    fn foo() { println!("function"); }
    // This resolves to the local closure since it shadows the item.
    foo(); // prints `closure`
}
```

Scopes
Pattern binding scopes
Pattern binding shadowing


The Rust Reference › Scopes › Generic parameter scopes

Generic parameters are declared in a [GenericParams] list. The scope of a generic parameter is within the item it is declared on.
All parameters are in scope within the generic parameter list regardless of the order they are declared. The following shows some examples where a parameter may be referenced before it is declared:
```rust
// The 'b bound is referenced before it is declared.
fn params_scope<'a: 'b, 'b>() {}

// The const N is referenced in the trait bound before it is declared.
fn f<T: SomeTrait<N>, const N: usize>() {}
```
Generic parameters are also in scope for type bounds and where clauses, for example:
```rust
// The <'a, U> for `SomeTrait` refer to the 'a and U parameters of `bounds_scope`.
fn bounds_scope<'a, T: SomeTrait<'a, U>, U>() {}

fn where_scope<'a, T, U>()
    where T: SomeTrait<'a, U>
{}
```
It is an error for [items] declared inside a function to refer to a generic parameter from their outer scope.
```rust,compile_fail
fn example<T>() {
    fn inner(x: T) {} // ERROR: can't use generic parameters from outer function
}
```


The Rust Reference › Scopes › Generic parameter scopes › Generic parameter shadowing

It is an error to shadow a generic parameter with the exception that items declared within functions are allowed to shadow generic parameter names from the function.
```rust
fn example<'a, T, const N: usize>() {
    // Items within functions are allowed to shadow generic parameter in scope.
    fn inner_lifetime<'a>() {} // OK
    fn inner_type<T>() {} // OK
    fn inner_const<const N: usize>() {} // OK
}
```
```rust,compile_fail
trait SomeTrait<'a, T, const N: usize> {
    fn example_lifetime<'a>() {} // ERROR: 'a is already in use
    fn example_type<T>() {} // ERROR: T is already in use
    fn example_const<const N: usize>() {} // ERROR: N is already in use
    fn example_mixed<const T: usize>() {} // ERROR: T is already in use
}
```

Scopes
Generic parameter scopes
Generic parameter shadowing


The Rust Reference › Scopes › Generic parameter scopes › Lifetime scopes › Impl trait restrictions

Lifetime parameters are declared in a [GenericParams] list and higher-ranked trait bounds.
The `'static` lifetime and [placeholder lifetime] `'_` have a special meaning and cannot be declared as a parameter.
[Constant] and [static] items and [const contexts] only ever allow `'static` lifetime references, so no other lifetime may be in scope within them. [Associated consts] do allow referring to lifetimes declared in their trait or implementation.
The scope of a lifetime parameter declared as a higher-ranked trait bound depends on the scenario where it is used.
* As a [TypeBoundWhereClauseItem] the declared lifetimes are in scope in the type and the type bounds.
* As a [TraitBound] the declared lifetimes are in scope within the bound type path.
* As a [BareFunctionType] the declared lifetimes are in scope within the function parameters and return type.
```rust

fn where_clause<T>()
    // 'a is in scope in both the type and the type bounds.
    where for <'a> &'a T: Trait<'a>
{}

fn bound<T>()
    // 'a is in scope within the bound.
    where T: for <'a> Trait<'a>
{}

// 'a is in scope in both the parameters and return type.
type FnExample = for<'a> fn(x: Example<'a>) -> Example<'a>;
```
[Impl trait] types can only reference lifetimes declared on a function or implementation.
```rust
// The `impl Trait2` here is not allowed to refer to 'b but it is allowed to
// refer to 'a.
fn foo<'a>() -> impl for<'b> Trait1<Item = impl Trait2<'a> + use<'a>> {
    // ...
}
```

Scopes
Generic parameter scopes
Lifetime scopes
Impl trait restrictions


The Rust Reference › Scopes › Loop label scopes

[Loop labels] may be declared by a [loop expression]. The scope of a loop label is from the point it is declared till the end of the loop expression. The scope does not extend into [items], [closures], [async blocks], [const arguments], [const contexts], and the iterator expression of the defining [`for` loop].
```rust
'a: for n in 0..3 {
    if n % 2 == 0 {
        break 'a;
    }
    fn inner() {
        // Using 'a here would be an error.
        // break 'a;
    }
}

// The label is in scope for the expression of `while` loops.
'a: while break 'a {}         // Loop does not run.
'a: while let _ = break 'a {} // Loop does not run.

// The label is not in scope in the defining `for` loop:
'a: for outer in 0..5 {
    // This will break the outer loop, skipping the inner loop and stopping
    // the outer loop.
    'a: for inner in { break 'a; 0..1 } {
        println!("{}", inner); // This does not run.
    }
    println!("{}", outer); // This does not run, either.
}

```
Loop labels may shadow labels of the same name in outer scopes. References to a label refer to the closest definition.
```rust
// Loop label shadowing example.
'a: for outer in 0..5 {
    'a: for inner in 0..5 {
        // This terminates the inner loop, but the outer loop continues to run.
        break 'a;
    }
}
```


The Rust Reference › Scopes › Prelude scopes

[Preludes] bring entities into scope of every module. The entities are not members of the module, but are implicitly queried during [name resolution].
The prelude names may be shadowed by declarations in a module.
The preludes are layered such that one shadows another if they contain entities of the same name. The order that preludes may shadow other preludes is the following where earlier entries may shadow later ones:
1. [Extern prelude]
2. [Tool prelude]
3. [`macro_use` prelude]
4. [Standard library prelude]
5. [Language prelude]


The Rust Reference › Scopes › `macro_rules` scopes

The scope of `macro_rules` macros is described in the [Macros By Example] chapter. The behavior depends on the use of the [`macro_use`] and [`macro_export`] attributes.


The Rust Reference › Scopes › Derive macro helper attributes

[Derive macro helper attributes] are in scope in the item where their corresponding [`derive` attribute] is specified. The scope extends from just after the `derive` attribute to the end of the item.
Helper attributes shadow other attributes of the same name in scope.


The Rust Reference › Scopes › `Self` scope

Although [`Self`] is a keyword with special meaning, it interacts with name resolution in a way similar to normal names.
The implicit `Self` type in the definition of a [struct], [enum], [union], [trait], or [implementation] is treated similarly to a generic parameter, and is in scope in the same way as a generic type parameter.
The implicit `Self` constructor in the value [namespace] of an [implementation] is in scope within the body of the implementation (the implementation's [associated items]).
```rust
// Self type within struct definition.
struct Recursive {
    f1: Option<Box<Self>>
}

// Self type within generic parameters.
struct SelfGeneric<T: Into<Self>>(T);

// Self value constructor within an implementation.
struct ImplExample();
impl ImplExample {
    fn example() -> Self { // Self type
        Self() // Self value constructor
    }
}
```


The Rust Reference › Preludes

A *prelude* is a collection of names that are automatically brought into scope of every module in a crate.
These prelude names are not part of the module itself: they are implicitly queried during [name resolution]. For example, even though something like [`Box`] is in scope in every module, you cannot refer to it as `self::Box` because it is not a member of the current module.
There are several different preludes:
- [Standard library prelude]
- [Extern prelude]
- [Language prelude]
- [`macro_use` prelude]
- [Tool prelude]


The Rust Reference › Preludes › Standard library prelude

Each crate has a standard library prelude, which consists of the names from a single standard library module.
The module used depends on the crate's edition, and on whether the [`no_std` attribute] is applied to the crate:
Edition | `no_std` not applied        | `no_std` applied
--------| --------------------------- | ----------------------------
2015    | [`std::prelude::rust_2015`] | [`core::prelude::rust_2015`]
2018    | [`std::prelude::rust_2018`] | [`core::prelude::rust_2018`]
2021    | [`std::prelude::rust_2021`] | [`core::prelude::rust_2021`]
2024    | [`std::prelude::rust_2024`] | [`core::prelude::rust_2024`]
[`std::prelude::rust_2015`] and [`std::prelude::rust_2018`] have the same contents as [`std::prelude::v1`].
[`core::prelude::rust_2015`] and [`core::prelude::rust_2018`] have the same contents as [`core::prelude::v1`].
When one of [`core::panic!`] or [`std::panic!`] is brought into scope due to the [standard library prelude], and a user-written [glob import] brings the other into scope, `rustc` currently allows use of `panic!`, even though it is ambiguous. The user-written glob import takes precedence to resolve this ambiguity.
For details, see [names.resolution.expansion.imports.ambiguity.panic-hack].


The Rust Reference › Preludes › Extern prelude

External crates imported with [`extern crate`] in the root module or provided to the compiler (as with the `--extern` flag with `rustc`) are added to the *extern prelude*. If imported with an alias such as `extern crate orig_name as new_name`, then the symbol `new_name` is instead added to the prelude.
The [`core`] crate is always added to the extern prelude.
The [`std`] crate is added as long as the [`no_std` attribute] is not specified in the crate root.
[!EDITION-2018]
In the 2015 edition, crates in the extern prelude cannot be referenced via [use declarations], so it is generally standard practice to include `extern crate` declarations to bring them into scope.
Beginning in the 2018 edition, [use declarations] can reference crates in the extern prelude, so it is considered unidiomatic to use `extern crate`.
Additional crates that ship with `rustc`, such as [`alloc`], and `test`, are not automatically included with the `--extern` flag when using Cargo. They must be brought into scope with an `extern crate` declaration, even in the 2018 edition.
```rust
extern crate alloc;
use alloc::rc::Rc;
```
Cargo does bring in `proc_macro` to the extern prelude for proc-macro crates only.


The Rust Reference › Preludes › Extern prelude › The `no_std` attribute

The *`no_std` attribute* causes the [`std`] crate to not be linked automatically and the [standard library prelude] to instead use the `core` prelude.
```rust,ignore
#![no_std]
```
Using `no_std` is useful when either the crate is targeting a platform that does not support the standard library or is purposefully not using the capabilities of the standard library. Those capabilities are mainly dynamic memory allocation (e.g. `Box` and `Vec`) and file and network capabilities (e.g. `std::fs` and `std::io`).
Using `no_std` does not prevent the standard library from being linked. It is still valid to write `extern crate std` in the crate or in one of its dependencies; this will cause the compiler to link the `std` crate into the program.
The `no_std` attribute uses the [MetaWord] syntax.
The `no_std` attribute may only be applied to the crate root.
The `no_std` attribute may be used any number of times on a form.
`rustc` lints against any use following the first.
The `no_std` attribute changes the [standard library prelude] to use the `core` prelude instead of the `std` prelude.
[!EDITION-2018]
Before the 2018 edition, `std` is injected into the crate root by default. If `no_std` is specified, `core` is injected instead. Starting with the 2018 edition, regardless of `no_std` being specified, neither is injected into the crate root.

Preludes
Extern prelude
The `no_std` attribute


The Rust Reference › Preludes › Language prelude

The language prelude includes names of types and attributes that are built-in to the language. The language prelude is always in scope.
It includes the following:
* [Type namespace]
    * [Boolean type] --- `bool`
    * [`char`]
    * [`str`]
    * [Integer types] --- `i8`, `i16`, `i32`, `i64`, `i128`, `u8`, `u16`, `u32`, `u64`, `u128`
    * [Machine-dependent integer types] --- `usize` and `isize`
    * [floating-point types] --- `f32` and `f64`
* [Macro namespace]
    * [Built-in attributes]
    * Built-in derive macros


The Rust Reference › Preludes › `macro_use` prelude

The `macro_use` prelude includes macros from external crates that were imported by the [`macro_use` attribute] applied to an [`extern crate`].


The Rust Reference › Preludes › Tool prelude

The tool prelude includes tool names for external tools in the [type namespace]. See the [tool attributes] section for more details.


The Rust Reference › Preludes › The `no_implicit_prelude` attribute

The *`no_implicit_prelude` [attribute]* is used to prevent implicit preludes from being brought into scope.
```rust
// The attribute can be applied to the crate root to affect
// all modules.
#![no_implicit_prelude]

// Or it can be applied to a module to only affect that module
// and its descendants.
#[no_implicit_prelude]
mod example {
    // ...
}
```
The `no_implicit_prelude` attribute uses the [MetaWord] syntax.
The `no_implicit_prelude` attribute may only be applied to the crate or to a module.
`rustc` ignores use in other positions but lints against it. This may become an error in the future.
The `no_implicit_prelude` attribute may be used any number of times on a form.
`rustc` lints against any use following the first.
The `no_implicit_prelude` attribute prevents the [standard library prelude], [extern prelude], [`macro_use` prelude], and the [tool prelude] from being brought into scope for the module and its descendants.
Despite `#![no_implicit_prelude]`, `rustc` currently brings certain macros implicitly into scope. Those macros are:
- [`assert!`]
- [`cfg!`]
- [`cfg_select!`]
- [`column!`]
- [`compile_error!`]
- [`concat!`]
- [`concat_bytes!`]
- [`env!`]
- [`file!`]
- [`format_args!`]
- [`include!`]
- [`include_bytes!`]
- [`include_str!`]
- [`line!`]
- [`module_path!`]
- [`option_env!`]
- [`panic!`]
- [`stringify!`]
- [`unreachable!`]
E.g., this works:
```rust
#![no_implicit_prelude]
fn main() { assert!(true); }
```

Preludes
The `no_implicit_prelude` attribute


The Rust Reference › Preludes › The `no_implicit_prelude` attribute

Don't rely on this behavior; it may be removed in the future. Always bring the items you need into scope explicitly when using `#![no_implicit_prelude]`.
For details, see Rust PR #62086 and Rust PR #139493.
The `no_implicit_prelude` attribute does not affect the [language prelude].
[!EDITION-2018]
In the 2015 edition, the `no_implicit_prelude` attribute does not affect the [`macro_use` prelude], and all macros exported from the standard library are still included in the `macro_use` prelude. Starting in the 2018 edition, the attribute does remove the `macro_use` prelude.


The Rust Reference › Paths

A *path* is a sequence of one or more path segments separated by `::` tokens. Paths are used to refer to [items], values, [types], [macros], and [attributes].
Two examples of simple paths consisting of only identifier segments:
```rust,ignore
x;
x::y::z;
```


The Rust Reference › Paths › Types of paths › Simple paths

```grammar,paths
SimplePath ->
    `::`? SimplePathSegment (`::` SimplePathSegment)*

SimplePathSegment ->
    IDENTIFIER | `super` | `self` | `crate` | `$crate`
```
Simple paths are used in [visibility] markers, [attributes], macros, and [`use`] items. For example:
```rust
use std::io::{self, Write};
mod m {
    #[clippy::cyclomatic_complexity = "0"]
    pub (in super) fn f1() {}
}
```


The Rust Reference › Paths › Types of paths › Paths in expressions

```grammar,paths
PathInExpression ->
    `::`? PathExprSegment (`::` PathExprSegment)*

PathExprSegment ->
    PathIdentSegment (`::` GenericArgs)?

PathIdentSegment ->
    IDENTIFIER | `super` | `self` | `Self` | `crate` | `$crate`

GenericArgs ->
      `<` GenericArgList? `>`
    | `(` TypeList? `)` (`->` TypeNoBounds)?

GenericArgList ->
    ( GenericArg `,` )* GenericArg `,`?

TypeList ->
    ( Type `,` )* Type `,`?

GenericArg ->
    Lifetime | Type | GenericArgsConst | GenericArgsBinding | GenericArgsBounds

GenericArgsConst ->
      BlockExpression
    | LiteralExpression
    | `-` LiteralExpression
    | SimplePathSegment

GenericArgsBinding ->
    TypePathSegment `=` Type

GenericArgsBounds ->
    TypePathSegment `:` Bounds?
```
Paths in expressions allow for paths with generic arguments to be specified. They are used in various places in [expressions] and [patterns].
The `::` token is required before the opening `<` for generic arguments to avoid ambiguity with the less-than operator. This is colloquially known as "turbofish" syntax.
```rust
(0..10).collect::<Vec<_>>();
Vec::<u8>::with_capacity(1024);
```
The order of generic arguments is restricted to lifetime arguments, then type arguments, then const arguments, then equality constraints.
Const arguments must be surrounded by braces unless they are a [literal], an [inferred const], or a single segment path. An [inferred const] may not be surrounded by braces.

Paths
Types of paths
Paths in expressions


The Rust Reference › Paths › Types of paths › Paths in expressions

```rust
mod m {
    pub const C: usize = 1;
}
const C: usize = m::C;
fn f<const N: usize>() -> [u8; N] { [0; N] }

let _ = f::<1>(); // Literal.
let _: [_; 1] = f::<_>(); // Inferred const.
let _: [_; 1] = f::<(((_)))>(); // Inferred const.
let _ = f::<C>(); // Single segment path.
let _ = f::<{ m::C }>(); // Multi-segment path must be braced.
```
```rust,compile_fail
fn f<const N: usize>() -> [u8; N] { [0; _] }
let _: [_; 1] = f::<{ _ }>();
//                    ^ ERROR `_` not allowed here
```
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 synthetic type parameters corresponding to `impl Trait` types are implicit, and these cannot be explicitly specified.


The Rust Reference › Paths › Qualified paths

```grammar,paths
QualifiedPathInExpression -> QualifiedPathType (`::` PathExprSegment)+

QualifiedPathType -> `<` Type (`as` TypePath)? `>`

QualifiedPathInType -> QualifiedPathType (`::` TypePathSegment)+
```
Fully qualified paths allow for disambiguating the path for [trait implementations] and for specifying canonical paths. When used in a type specification, it supports using the type syntax specified below.
```rust
struct S;
impl S {
    fn f() { println!("S"); }
}
trait T1 {
    fn f() { println!("T1 f"); }
}
impl T1 for S {}
trait T2 {
    fn f() { println!("T2 f"); }
}
impl T2 for S {}
S::f();  // Calls the inherent impl.
<S as T1>::f();  // Calls the T1 trait function.
<S as T2>::f();  // Calls the T2 trait function.
```


The Rust Reference › Paths › Qualified paths › Paths in types

```grammar,paths
TypePath -> `::`? TypePathSegment (`::` TypePathSegment)*

TypePathSegment -> PathIdentSegment (`::`? GenericArgs)?
```
Type paths are used within type definitions, trait bounds, and qualified paths.
Although the `::` token is allowed before the generics arguments, it is not required because there is no ambiguity like there is in [PathInExpression].
```rust
impl ops::Index<ops::Range<usize>> for S { /*...*/ }
fn i<'a>() -> impl Iterator<Item = ops::Example<'a>> {
    // ...
}
type G = std::boxed::Box<dyn std::ops::FnOnce(isize) -> isize>;
```


The Rust Reference › Paths › Path qualifiers

Paths can be denoted with various leading qualifiers to change the meaning of how it is resolved.
[`use` declarations] have additional behaviors and restrictions for `self`, `super`, `crate`, and `$crate`.


The Rust Reference › Paths › Path qualifiers › `::`

Paths starting with `::` are considered to be *global paths* where the segments of the path start being resolved from a place which differs based on edition. Each identifier in the path must resolve to an item.
[!EDITION-2018]
In the 2015 Edition, identifiers resolve from the "crate root" (`crate::` in the 2018 edition), which contains a variety of different items, including external crates, default crates such as `std` or `core`, and items in the top level of the crate (including `use` imports).
Beginning with the 2018 Edition, paths starting with `::` resolve from crates in the [extern prelude]. That is, they must be followed by the name of a crate.
```rust
pub fn foo() {
    // In the 2018 edition, this accesses `std` via the extern prelude.
    // In the 2015 edition, this accesses `std` via the crate root.
    let now = ::std::time::Instant::now();
    println!("{:?}", now);
}
```
```rust,edition2015
// 2015 Edition
mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        ::a::foo(); // call `a`'s foo function
        // In Rust 2018, `::a` would be interpreted as the crate `a`.
    }
}
```


The Rust Reference › Paths › Path qualifiers › `self`

`self` resolves the path relative to the current module.
`self` may only be used as the first segment of a path (without a preceding `::`) or as the last segment (preceded by `::`).
When `self` appears as the last segment of a path, it refers to the entity named by the preceding segment. The preceding path must resolve to a [module], [enumeration], or [trait].
```rust
mod m {
    pub enum E { V1 }
    pub trait Tr {}
    pub(in crate::m::self) fn g() {} // OK: Modules can be parents of `self`.
}
type Ty = m::E::self; // OK: Enumerations can be parents of `self`.
fn f<T: m::Tr::self>() {} // OK: Traits can be parents of `self`.
```
```rust,compile_fail,E0223
struct S;
type Ty = S::self; // ERROR: Structs cannot be parents of `self`.
```
See [items.use.self] for additional rules about `self` in `use` declarations.
In a method body, a path which consists of a single `self` segment resolves to the method's self parameter.
```rust
fn foo() {}
fn bar() {
    self::foo();
}
struct S(bool);
impl S {
  fn baz(self) {
        self.0;
    }
}
```


The Rust Reference › Paths › Path qualifiers › `Self`

`Self`, with a capital "S", is used to refer to the current type being implemented or defined. It may be used in the following situations:
* In a [trait] definition, it refers to the type implementing the trait.
* In an [implementation], it refers to the type being implemented. When implementing a tuple or unit [struct], it also refers to the constructor in the [value namespace].
* In the definition of a [struct], [enumeration], or [union], it refers to the type being defined. The definition is not allowed to be infinitely recursive (there must be an indirection).
The scope of `Self` behaves similarly to a generic parameter; see the [`Self` scope] section for more details.
`Self` can only be used as the first segment, without a preceding `::`.
The `Self` path cannot include generic arguments (as in `Self::<i32>`).


The Rust Reference › Paths › Path qualifiers › `Self`

```rust
trait T {
    type Item;
    const C: i32;
    // `Self` will be whatever type that implements `T`.
    fn new() -> Self;
    // `Self::Item` will be the type alias in the implementation.
    fn f(&self) -> Self::Item;
}
struct S;
impl T for S {
    type Item = i32;
    const C: i32 = 9;
    fn new() -> Self {           // `Self` is the type `S`.
        S
    }
    fn f(&self) -> Self::Item {  // `Self::Item` is the type `i32`.
        Self::C                  // `Self::C` is the constant value `9`.
    }
}

// `Self` is in scope within the generics of a trait definition,
// to refer to the type being defined.
trait Add<Rhs = Self> {
    type Output;
    // `Self` can also reference associated items of the
    // type being implemented.
    fn add(self, rhs: Rhs) -> Self::Output;
}

struct NonEmptyList<T> {
    head: T,
    // A struct can reference itself (as long as it is not
    // infinitely recursive).
    tail: Option<Box<Self>>,
}
```


The Rust Reference › Paths › Path qualifiers › `super`

`super` in a path resolves to the parent module.
It may only be used in leading segments of the path, possibly after an initial `self` segment.
```rust
mod a {
    pub fn foo() {}
}
mod b {
    pub fn foo() {
        super::a::foo(); // call a's foo function
    }
}
```
`super` may be repeated several times after the first `super` or `self` to refer to ancestor modules.
```rust
mod a {
    fn foo() {}

    mod b {
        mod c {
            fn foo() {
                super::super::foo(); // call a's foo function
                self::super::super::foo(); // call a's foo function
            }
        }
    }
}
```


The Rust Reference › Paths › Path qualifiers › `crate`

`crate` resolves the path relative to the current crate.
`crate` can only be used as the first segment, without a preceding `::`.
```rust
fn foo() {}
mod a {
    fn bar() {
        crate::foo();
    }
}
```


The Rust Reference › Paths › Path qualifiers › `$crate`

[`$crate`] is only used within [macro transcribers], and can only be used as the first segment, without a preceding `::`.
[`$crate`] will expand to a path to access items from the top level of the crate where the macro is defined, regardless of which crate the macro is invoked.
```rust
pub fn increment(x: u32) -> u32 {
    x + 1
}

#[macro_export]
macro_rules! inc {
    ($x:expr) => ( $crate::increment($x) )
}
```


The Rust Reference › Paths › Canonical paths

Each item defined in a module or implementation has a *canonical path* that corresponds to where within its crate it is defined.
All other paths to these items are aliases.
The canonical path is defined as a *path prefix* appended by the path segment the item itself defines.
[Implementations] and [use declarations] do not have canonical paths, although the items that implementations define do have them. Items defined in block expressions do not have canonical paths. Items defined in a module that does not have a canonical path do not have a canonical path. Associated items defined in an implementation that refers to an item without a canonical path, e.g. as the implementing type, the trait being implemented, a type parameter or bound on a type parameter, do not have canonical paths.
The path prefix for modules is the canonical path to that module.
For bare implementations, it is the canonical path of the item being implemented surrounded by angle (`<>`) brackets.
For [trait implementations], it is the canonical path of the item being implemented followed by `as` followed by the canonical path to the trait all surrounded in angle (`<>`) brackets.
The canonical path is only meaningful within a given crate. There is no global namespace across crates; an item's canonical path merely identifies it within the crate.


The Rust Reference › Paths › Canonical paths

```rust
// Comments show the canonical path of the item.

mod a { // crate::a
    pub struct Struct; // crate::a::Struct

    pub trait Trait { // crate::a::Trait
        fn f(&self); // crate::a::Trait::f
    }

    impl Trait for Struct {
        fn f(&self) {} // <crate::a::Struct as crate::a::Trait>::f
    }

    impl Struct {
        fn g(&self) {} // <crate::a::Struct>::g
    }
}

mod without { // crate::without
    fn canonicals() { // crate::without::canonicals
        struct OtherStruct; // None

        trait OtherTrait { // None
            fn g(&self); // None
        }

        impl OtherTrait for OtherStruct {
            fn g(&self) {} // None
        }

        impl OtherTrait for crate::a::Struct {
            fn g(&self) {} // None
        }

        impl crate::a::Trait for OtherStruct {
            fn f(&self) {} // None
        }
    }
}

```


The Rust Reference › Name resolution

_Name resolution_ is the process of tying paths and other identifiers to the declarations of those entities. Names are segregated into different [namespaces], allowing entities in different namespaces to share the same name without conflict. Each name is valid within a [scope], or a region of source text where that name may be referenced. Access to a name may be restricted based on its [visibility].
Name resolution is split into three stages throughout the compilation process. The first stage, *expansion-time resolution*, resolves all [`use` declarations] and [macro invocations]. The second stage, *primary resolution*, resolves all names that have not yet been resolved and that do not depend on type information to resolve. The last stage, *type-relative resolution*, resolves the remaining names once type information is available.
Expansion-time resolution is also known as *early resolution*. Primary resolution is also known as *late resolution*.


The Rust Reference › Name resolution › General

The rules within this section apply to all stages of name resolution.


The Rust Reference › Name resolution › General › Scopes

This is a placeholder for future expansion about resolution of names within various scopes.


The Rust Reference › Name resolution › Expansion-time name resolution

Expansion-time name resolution is the stage of name resolution necessary to complete macro expansion and fully generate a crate's [AST]. This stage requires the resolution of macro invocations and `use` declarations. Resolving `use` declarations is required for macro invocations that resolve via [path-based scope]. Resolving macro invocations is required in order to expand them.
After expansion-time name resolution, the AST must not contain any unexpanded macro invocations. Every macro invocation resolves to a valid definition that exists in the final AST or in an external crate.
```rust,compile_fail
m!(); // ERROR: Cannot find macro `m` in this scope.
```
The resolution of names must be stable. After expansion, names in the fully expanded AST must resolve to the same definition regardless of the order in which macros are expanded and imports are resolved.
All name resolution candidates selected during macro expansion are considered speculative. Once the crate has been fully expanded, all speculative import resolutions are validated to ensure that macro expansion did not introduce any new ambiguities.
Due to the iterative nature of macro expansion, this causes so-called time traveling ambiguities, such as when a macro or glob import introduces an item that is ambiguous with its own base path.
```rust,compile_fail,E0659
macro_rules! f {
    () => {
        mod m {
            pub(crate) use f;
        }
    }
}
f!();

const _: () = {
    // Initially, we speculatively resolve `m` to the module in
    // the crate root.
    //
    // Expansion of `f` introduces a second `m` module inside this
    // body.
    //
    // Expansion-time resolution finalizes resolutions by re-
    // resolving all imports and macro invocations, sees the
    // introduced ambiguity and reports it as an error.
    m::f!(); // ERROR: `m` is ambiguous.
};
```

Name resolution
Expansion-time name resolution


The Rust Reference › Name resolution › Expansion-time name resolution › Imports

All `use` declarations are fully resolved during this stage of resolution. [Type-relative paths] cannot be resolved at this stage and will produce an error.
```rust,no_run
mod m {
    pub const C: () = ();
    pub enum E { V }
    pub type A = E;
    impl E {
        pub const C: () = ();
    }
}

// Valid imports resolved at expansion-time:
use m::C; // OK.
use m::E; // OK.
use m::A; // OK.
use m::E::V; // OK.

// Valid expressions resolved during type-relative resolution:
let _ = m::A::V; // OK.
let _ = m::E::C; // OK.
```
```rust,compile_fail,E0432
// Invalid type-relative imports that can't resolve at expansion-time:
use m::A::V; // ERROR: Unresolved import `m::A::V`.
use m::E::C; // ERROR: Unresolved import `m::E::C`.
```
Names introduced via `use` declarations in an [outer scope] are shadowed by candidates in the same namespace with the same name from an inner scope except where otherwise restricted by [name resolution ambiguities].
```rust,no_run
pub mod m1 {
    pub mod ambig {
        pub const C: u8 = 1;
    }
}

pub mod m2 {
    pub mod ambig {
        pub const C: u8 = 2;
    }
}

// This introduces the name `ambig` in the outer scope.
use m1::ambig;
const _: () = {
    // This shadows `ambig` in the inner scope.
    use m2::ambig;
    // The inner candidate is selected here
    // as the resolution of `ambig`.
    use ambig::C;
    assert!(C == 2);
};
```

Name resolution
Expansion-time name resolution
Imports


The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities

Shadowing of names introduced via `use` declarations within a single scope is permitted in the following situations:
- [`use` glob shadowing]
- [Macro textual scope shadowing]
There are certain situations during expansion-time resolution where there are multiple macro definitions, `use` declarations, or modules an import or macro invocation's name could refer to where the compiler cannot consistently determine which candidate should shadow the other. Shadowing cannot be permitted in these situations and the compiler instead emits ambiguity errors.
Names may not be resolved through ambiguous glob imports. Glob imports are allowed to import conflicting names in the same namespace as long as the name is not used. Names with conflicting candidates from ambiguous glob imports may still be shadowed by non-glob imports and used without producing an error. The errors occur at time of use, not time of import.
```rust,compile_fail,E0659
mod m1 {
    pub struct Ambig;
}

mod m2 {
    pub struct Ambig;
}

// OK: This brings conficting names in the same namespace into scope
// but they have not been used yet.
use m1::*;
use m2::*;

const _: () = {
    // The error happens when the name with the conflicting candidates
    // is used.
    let x = Ambig; // ERROR: `Ambig` is ambiguous.
};
```
```rust,no_run
const _: () = {
    // This is permitted, since resolution is not through the
    // ambiguous globs.
    struct Ambig;
    let x = Ambig; // OK.
};
```
Multiple glob imports are allowed to import the same name, and that name is allowed to be used if the imports are of the same item (following reexports). The visibility of the name is the maximum visibility of the imports.

Name resolution
Expansion-time name resolution
Imports
Ambiguities


The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities

```rust,no_run
mod m1 {
    pub struct Ambig;
}

mod m2 {
    // This reexports the same `Ambig` item from a second module.
    pub use super::m1::Ambig;
}

mod m3 {
    // These both import the same `Ambig`.
    //
    // The visibility of `Ambig` is `pub` because that is the
    // maximum visibility between these two `use` declarations.
    pub use super::m1::*;
    use super::m2::*;
}

mod m4 {
    // `Ambig` can be used through the `m3` globs and still has
    // `pub` visibility.
    pub use crate::m3::Ambig;
}

const _: () = {
    // Therefore, we can use it here.
    let _ = m4::Ambig; // OK.
};
```
Names in imports and macro invocations may not be resolved through glob imports when there is another candidate available in an [outer scope].
When one of [`core::panic!`] or [`std::panic!`] is brought into scope due to the [standard library prelude], and a user-written [glob import] brings the other into scope, `rustc` currently allows use of `panic!`, even though it is ambiguous. The user-written glob import takes precedence to resolve this ambiguity.
In Rust 2021 and later, [`core::panic!`] and [`std::panic!`] operate identically. But in earlier editions, they differ; only [`std::panic!`] accepts a [`String`] as the format argument.
E.g., this is an error:
```rust,edition2018,compile_fail,E0308
extern crate core;
use ::core::prelude::v1::*;
fn main() {
    panic!(std::string::String::new()); // ERROR.
}
```
And this is accepted:


The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities

```rust,edition2018,ignore
#![no_std]
extern crate std;
use ::std::prelude::v1::*;
fn main() {
    panic!(std::string::String::new()); // OK.
}
```
Don't rely on this behavior; the plan is to remove it.
For details, see Rust issue #147319.
```rust,compile_fail,E0659
mod glob {
    pub mod ambig {
        pub struct Name;
    }
}

// Outer `ambig` candidate.
pub mod ambig {
    pub struct Name;
}

const _: () = {
    // Cannot resolve `ambig` through this glob
    // because of the outer `ambig` candidate above.
    use glob::*;
    use ambig::Name; // ERROR: `ambig` is ambiguous.
};
```
```rust,compile_fail,E0659
// As above, but with macros.
pub mod m {
    macro_rules! f {
        () => {};
    }
    pub(crate) use f;
}
pub mod glob {
    macro_rules! f {
        () => {};
    }
    pub(crate) use f as ambig;
}

use m::f as ambig;

const _: () = {
    use glob::*;
    ambig!(); // ERROR: `ambig` is ambiguous.
};
```
These ambiguity errors are specific to expansion-time resolution. Having multiple candidates available for a given name during later stages of resolution is not considered an error. So long as none of the imports themselves are ambiguous, there will always be a single unambiguous closest resolution.


The Rust Reference › Name resolution › Expansion-time name resolution › Imports › Ambiguities

```rust,no_run
mod glob {
    pub const AMBIG: u8 = 1;
}

mod outer {
    pub const AMBIG: u8 = 2;
}

use outer::AMBIG;

const C: () = {
    use glob::*;
    assert!(AMBIG == 1);
    //      ^---- This `AMBIG` is resolved during primary resolution.
};
```
Names may not be resolved through ambiguous macro reexports. Macro reexports are ambiguous when they would shadow a textual macro candidate for the same name in an [outer scope].
```rust,compile_fail,E0659
// Textual macro candidate.
macro_rules! ambig {
    () => {}
}

// Path-based macro candidate.
macro_rules! path_based {
    () => {}
}

pub fn f() {
    // This reexport of the `path_based` macro definition
    // as `ambig` may not shadow the `ambig` macro definition
    // which is resolved via textual macro scope.
    use path_based as ambig;
    ambig!(); // ERROR: `ambig` is ambiguous.
}
```
This restriction is needed due to implementation details in the compiler, specifically the current scope visitation logic and the complexity of supporting this behavior. This ambiguity error may be removed in the future.


The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities

Macros are resolved by iterating through the available scopes to find the available candidates. Macros are split into two sub-namespaces, one for function-like macros, and the other for attributes and derives. Resolution candidates from the incorrect sub-namespace are ignored.
The available scope kinds are visited in the following order. Each of these scope kinds represent one or more scopes.
* [Derive helpers]
* [Textual scope macros]
* [Path-based scope macros]
* [`macro_use` prelude]
* [Standard library prelude]
* [Builtin attributes]
The compiler will attempt to resolve derive helpers that are used before their associated macro introduces them into scope. This scope is visited after the scope for resolving derive helper candidates that are correctly in scope. This behavior is slated for removal.
For more info see [derive helper scope].
This visitation order may change in the future, such as interleaving the visitation of textual and path-based scope candidates based on their lexical scopes.
[!EDITION-2018]
Starting in edition 2018 the `#[macro_use]` prelude is not visited when [`#[no_implicit_prelude]`][names.preludes.no_implicit_prelude] is present.
The names `cfg` and `cfg_attr` are reserved in the macro attribute [sub-namespace].
Names may not be resolved through ambiguous candidates inside of macro expansions. Candidates inside of macro expansions are ambiguous when they would shadow a candidate for the same name from outside of the first candidate's macro expansion and the invocation of the name being resolved is also from outside of the first candidate's macro expansion.

Name resolution
Expansion-time name resolution
Macros
Ambiguities


The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities

```rust,compile_fail,E0659
macro_rules! define_ambig {
    () => {
        macro_rules! ambig {
            () => {}
        }
    }
}

// Introduce outer candidate definition for `ambig` macro invocation.
macro_rules! ambig {
    () => {}
}

// Introduce a second candidate definition for `ambig` inside of a
// macro expansion.
define_ambig!();

// The definition of `ambig` from the second invocation
// of `define_ambig` is the innermost canadidate.
//
// The definition of `ambig` from the first invocation of
// `define_ambig` is the second candidate.
//
// The compiler checks that the first candidate is inside of a macro
// expansion, that the second candidate is not from within the same
// macro expansion, and that the name being resolved is not from
// within the same macro expansion.
ambig!(); // ERROR: `ambig` is ambiguous.
```
The reverse is not considered ambiguous.
```rust,no_run
// Swap order of definitions.
define_ambig!();
macro_rules! ambig {
    () => {}
}
// The innermost candidate is now less expanded so it may shadow more
// the macro expanded definition above it.
ambig!();
```
Nor is it ambiguous if the invocation being resolved is within the innermost candidate's expansion.
```rust,no_run
macro_rules! ambig {
    () => {}
}

macro_rules! define_and_invoke_ambig {
    () => {
        // Define innermost candidate.
        macro_rules! ambig {
            () => {}
        }

        // Invocation of `ambig` is in the same expansion as the
        // innermost candidate.
        ambig!(); // OK
    }
}

define_and_invoke_ambig!();
```


The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities

It doesn't matter if both definitions come from invocations of the same macro; the outermost candidate is still considered "less expanded" because it is not within the expansion containing the innermost candidate's definition.
```rust,compile_fail,E0659
define_ambig!();
define_ambig!();
ambig!(); // ERROR: `ambig` is ambiguous.
```
This also applies to imports so long as the innermost candidate for the name is from within a macro expansion.
```rust,compile_fail,E0659
macro_rules! define_ambig {
    () => {
        mod ambig {
            pub struct Name;
        }
    }
}

mod ambig {
    pub struct Name;
}

const _: () = {
    // Introduce innermost candidate for
    // `ambig` mod in this macro expansion.
    define_ambig!();
    use ambig::Name; // ERROR: `ambig` is ambiguous.
};
```
User-defined attributes or derive macros may not shadow built-in non-macro attributes (e.g. inline).
```rust,ignore
// with-helper/src/lib.rs
#[proc_macro_derive(WithHelperAttr, attributes(non_exhaustive))]
//                                             ^^^^^^^^^^^^^^
//                                   User-defined attribute candidate.
// ...
```
```rust,ignore
// src/lib.rs
#[derive(with_helper::WithHelperAttr)]
#[non_exhaustive] // ERROR: `non_exhaustive` is ambiguous.
struct S;
```
This applies regardless of the name the built-in attribute is a candidate for:
```rust,ignore
// with-helper/src/lib.rs
#[proc_macro_derive(WithHelperAttr, attributes(helper))]
//                                             ^^^^^^
//                                 User-defined attribute candidate.
// ...
```


The Rust Reference › Name resolution › Expansion-time name resolution › Macros › Ambiguities

```rust,ignore
// src/lib.rs
use inline as helper;
//            ^----- Built-in attribute candidate via reexport.

#[derive(with_helper::WithHelperAttr)]
#[helper] // ERROR: `helper` is ambiguous.
struct S;
```


The Rust Reference › Name resolution › Primary name resolution

This is a placeholder for future expansion about primary name resolution.


The Rust Reference › Name resolution › Type-relative resolution

This is a placeholder for future expansion about type-dependent resolution.

Name resolution
Type-relative resolution


The Rust Reference › Visibility and privacy

```grammar,items
Visibility ->
      `pub`
    | `pub` `(` `crate` `)`
    | `pub` `(` `self` `)`
    | `pub` `(` `super` `)`
    | `pub` `(` `in` SimplePath `)`
```
These two terms are often used interchangeably, and what they are attempting to convey is the answer to the question "Can this item be used at this location?"
Rust's name resolution operates on a global hierarchy of namespaces. Each level in the hierarchy can be thought of as some item. The items are one of those mentioned above, but also include external crates. Declaring or defining a new module can be thought of as inserting a new tree into the hierarchy at the location of the definition.
To control whether interfaces can be used across modules, Rust checks each use of an item to see whether it should be allowed or not. This is where privacy warnings are generated, or otherwise "you used a private item of another module and weren't allowed to."
By default, everything is *private*, with two exceptions: Associated items in a `pub` Trait are public by default; Enum variants in a `pub` enum are also public by default. When an item is declared as `pub`, it can be thought of as being accessible to the outside world. For example:
```rust
// Declare a private struct
struct Foo;

// Declare a public struct with a private field
pub struct Bar {
    field: i32,
}

// Declare a public enum with two public variants
pub enum State {
    PubliclyAccessibleState,
    PubliclyAccessibleState2,
}
```
With the notion of an item being either public or private, Rust allows item accesses in two cases:


The Rust Reference › Visibility and privacy

1. If an item is public, then it can be accessed externally from some module `m` if you can access all the item's ancestor modules from `m`. You can also potentially be able to name the item through re-exports. See below.
2. If an item is private, it may be accessed by the current module and its descendants.
These two cases are surprisingly powerful for creating module hierarchies exposing public APIs while hiding internal implementation details. To help explain, here's a few use cases and what they would entail:
* A library developer needs to expose functionality to crates which link against their library. As a consequence of the first case, this means that anything which is usable externally must be `pub` from the root down to the destination item. Any private item in the chain will disallow external accesses.
* A crate needs a global available "helper module" to itself, but it doesn't want to expose the helper module as a public API. To accomplish this, the root of the crate's hierarchy would have a private module which then internally has a "public API". Because the entire crate is a descendant of the root, then the entire local crate can access this private module through the second case.
* When writing unit tests for a module, it's often a common idiom to have an immediate child of the module to-be-tested named `mod test`. This module could access any items of the parent module through the second case, meaning that internal implementation details could also be seamlessly tested from the child module.
In the second case, it mentions that a private item "can be accessed" by the current module and its descendants, but the exact meaning of accessing an item depends on what the item is.


The Rust Reference › Visibility and privacy

Accessing a module, for example, would mean looking inside of it (to import more items). On the other hand, accessing a function would mean that it is invoked. Additionally, path expressions and import statements are considered to access an item in the sense that the import/expression is only valid if the destination is in the current visibility scope.
Here's an example of a program which exemplifies the three cases outlined above:


The Rust Reference › Visibility and privacy

```rust
// This module is private, meaning that no external crate can access this
// module. Because it is private at the root of this current crate, however, any
// module in the crate may access any publicly visible item in this module.
mod crate_helper_module {

    // This function can be used by anything in the current crate
    pub fn crate_helper() {}

    // This function *cannot* be used by anything else in the crate. It is not
    // publicly visible outside of the `crate_helper_module`, so only this
    // current module and its descendants may access it.
    fn implementation_detail() {}
}

// This function is "public to the root" meaning that it's available to external
// crates linking against this one.
pub fn public_api() {}

// Similarly to 'public_api', this module is public so external crates may look
// inside of it.
pub mod submodule {
    use crate::crate_helper_module;

    pub fn my_method() {
        // Any item in the local crate may invoke the helper module's public
        // interface through a combination of the two rules above.
        crate_helper_module::crate_helper();
    }

    // This function is hidden to any module which is not a descendant of
    // `submodule`
    fn my_implementation() {}

    #[cfg(test)]
    mod test {

        #[test]
        fn test_my_implementation() {
            // Because this module is a descendant of `submodule`, it's allowed
            // to access private items inside of `submodule` without a privacy
            // violation.
            super::my_implementation();
        }
    }
}

```
For a Rust program to pass the privacy checking pass, all paths must be valid accesses given the two rules above. This includes all use statements, expressions, types, etc.