Constant evaluation is the process of computing the result of expressions during compilation. Only a subset of all expressions can be evaluated at compile-time.
Certain types of expressions can be evaluated at compile time. These are called
constant expressions and are required in const contexts. In
other places, such as in
constant expressions may be evaluated at compile time. If errors, such as out
of bounds array indexing or overflow occurs,
then it is a compiler error if the value must be evaluated at compile time,
otherwise it is just a warning, but the code will most likely panic when run.
The following expressions are constant expressions, so long as any operands are
also constant expressions and do not cause any
to be ran.
- Paths to functions and constants. Recursively defining constants is not allowed.
- Tuple expressions.
- Array expressions.
- Struct expressions.
- Enum variant expressions.
- Block expressions, including
unsafeblocks, which only contain items and possibly a constant tail expression.
- Field expressions.
- Index expressions, array indexing or slice with a
- Range expressions.
- Closure expressions which don't capture variables from the environment.
- Built in negation, arithmetic, logical, comparison or lazy boolean
operators used on integer and floating point types,
- Shared borrows, except if applied to a type with interior mutability.
- The dereference operator.
- Grouped expressions.
- Cast expressions, except pointer to address and function pointer to address casts.
- Calls of const functions and const methods
A const context is one of the following: