Constant items
Syntax
ConstantItem :
const
( IDENTIFIER |_
):
Type (=
Expression )?;
A constant item is an optionally named constant value which is not associated
with a specific memory location in the program. Constants are essentially inlined
wherever they are used, meaning that they are copied directly into the relevant
context when used. This includes usage of constants from external crates, and
non-Copy
types. References to the same constant are not necessarily
guaranteed to refer to the same memory address.
Constants must be explicitly typed. The type must have a 'static
lifetime: any
references in the initializer must have 'static
lifetimes.
Constants may refer to the address of other constants, in which case the
address will have elided lifetimes where applicable, otherwise – in most cases
– defaulting to the static
lifetime. (See static lifetime
elision.) The compiler is, however, still at liberty to translate the constant
many times, so the address referred to may not be stable.
The constant expression may only be omitted in a trait definition.
Constants with Destructors
Constants can contain destructors. Destructors are run when the value goes out of scope.
Unnamed constant
Unlike an associated constant, a free constant may be unnamed by using an underscore instead of the name. For example:
As with underscore imports, macros may safely emit the same unnamed constant in the same scope more than once. For example, the following should not produce an error:
Evaluation
Free constants are always evaluated at compile-time to surface panics. This happens even within an unused function: