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 forms of expressions, called constant expressions, can be evaluated at compile time. In const contexts, these are the only allowed expressions, and are always evaluated at compile time. In other places, such as let statements, 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.
if letand match expressions.
A const context is one of the following:
A const fn is a function that one is permitted to call from a const context. Declaring a function
const has no effect on any existing uses, it only restricts the types that arguments and the return type may use, as well as prevent various expressions from being used within it.
Notable features that const contexts have, but const fn haven't are:
Copy. So you cannot do anything with them but copy/move them around.
Conversely, the following are possible in a const function, but not in a const context:
© 2010 The Rust Project Developers
Licensed under the Apache License, Version 2.0 or the MIT license, at your option.