Underscore

The underscore is a reserved identifier in Rust and serves different purposes depending on the context. It usually means that something is ignored.

Underscores in patterns
in a pattern is called a wildcard, because it matches anything:

The wildcard is not a variable binding, because  can't be used as a variable.

Underscores in bindings
Since  accepts a pattern,   can be used to ignore a   value such as a  in order to suppress compiler warnings.

Note that it's often better to unwrap the result instead, to make sure that errors aren't silently discarded.

Drop order for wildcard patterns
When a variable goes out of scope, it is dropped and its destructor is called, if it has one. However,  patterns behave a bit different than variables. The reference states :

"Unlike identifier patterns, it does not copy, move or borrow the value it matches."

In,  ,   and   blocks, values matched as   are dropped after the variable bindings. For example:

Function/closure parameters that are ignored with  have the same drop order as variables:

In  bindings, a   pattern does nothing:   is equivalent to just , which drops the return value immediately.

Note that variables can be prefixed with a  to silence "unused variable" warnings, but this does not affect drop order:

Underscores in types
Underscores can be used to omit type declarations. For example, it can be used to specify only part of a type, and let Rust infer the rest:

Anonymous lifetime
The anonymous lifetime can be used where an explicit lifetime must be specified, even though it is used only once:

The  block above is more concise thanks to the anonymous lifetime. The  function's return type could just be written as , but the anonymous lifetime makes it clearer that the struct borrows something.

Anonymous items
items can be anonymous, by writing  instead of a name:

These aren't too useful though, since there is no way to use them at runtime. However, they can be used to evaluate something at compile time, e.g. to verify that something compiles.