Constant evaluation

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.

Constant expressions

Certain forms of expressions, called constant expressions, can be evaluated at compile time.

Expressions in a const context must be constant expressions.

Expressions in const contexts are always evaluated at compile time.

Outside of const contexts, constant expressions may be, but are not guaranteed to be, evaluated at compile time.

Behaviors such as out of bounds array indexing or overflow are compiler errors if the value must be evaluated at compile time (i.e. in const contexts). Otherwise, these behaviors are warnings, but will likely panic at run-time.

The following expressions are constant expressions, so long as any operands are also constant expressions and do not cause any Drop::drop calls to be run.

Const context

A const context is one of the following:

Array type length expressions, array repeat length expressions, and const generic arguments are restricted in their use of outer generic parameters: such an expression must either be a single const generic parameter, or an expression that does not reference any generic parameters.

Const functions

A const function is a function that can be called from a const context. It is defined with the const qualifier, and also includes tuple struct and tuple enum variant constructors.

Example

const fn square(x: i32) -> i32 { x * x }

const VALUE: i32 = square(12);

When called from a const context, a const function is interpreted by the compiler at compile time. The interpretation happens in the environment of the compilation target and not the host. So usize is 32 bits if you are compiling against a 32 bit system, irrelevant of whether you are building on a 64 bit or a 32 bit system.

When a const function is called from outside a const context, it behaves the same as if it did not have the const qualifier.

The body of a const function may only use constant expressions.

Const functions are not allowed to be async.

The types of a const function's parameters and return type are restricted to those that are compatible with a const context.