Constant evaluation
Constant evaluation is the process of computing the result ofexpressions during compilation. Only a subset of all expressionscan be evaluated at compile-time.
Constant expressions
Certain forms of expressions, called constant expressions, can be evaluated atcompile time.
Inconst contexts, these are the only allowedexpressions, and are always evaluated at compile time.
In other places, such aslet statements, constant expressionsmay be, but are not guaranteed to be, evaluated at compile time.
Behaviors such as out of boundsarray indexing oroverflow are compiler errors if the valuemust be evaluated at compile time (i.e. in const contexts). Otherwise, thesebehaviors are warnings, but will likely panic at run-time.
The following expressions are constant expressions, so long as any operands arealso constant expressions and do not cause anyDrop::drop callsto be run.
Paths tostatics with these restrictions:
- Writes to
staticitems are not allowed in any constant evaluation context. - Reads from
externstatics are not allowed in any constant evaluation context. - If the evaluation isnot carried out in an initializer of a
staticitem, then reads from any mutablestaticare not allowed. A mutablestaticis astatic mutitem, or astaticitem with an interior-mutable type.
These requirements are checked only when the constant is evaluated. In other words, having such accesses syntactically occur in const contexts is allowed as long as they never get executed.
- Writes to
- Struct expressions.
- Block expressions, including
unsafeandconstblocks.- let statements and thus irrefutablepatterns, including mutable bindings
- assignment expressions
- compound assignment expressions
- expression statements
- Field expressions.
- Index expressions,array indexing orslice with a
usize.
- Closure expressions which don’t capture variables from the environment.
- Built-innegation,arithmetic,logical,comparison orlazy booleanoperators used on integer and floating point types,
bool, andchar.
All forms ofborrows, including raw borrows, except borrows of expressions whose temporary scopes would be extended (seetemporary lifetime extension) to the end of the program and which are either:
- Mutable borrows.
- Shared borrows of expressions that result in values withinterior mutability.
#![allow(unused)]fn main() {// Due to being in tail position, this borrow extends the scope of the// temporary to the end of the program. Since the borrow is mutable,// this is not allowed in a const expression.const C: &u8 = &mut 0; // ERROR not allowed}#![allow(unused)]fn main() {// Const blocks are similar to initializers of `const` items.let _: &u8 = const { &mut 0 }; // ERROR not allowed}#![allow(unused)]fn main() {use core::sync::atomic::AtomicU8;// This is not allowed as 1) the temporary scope is extended to the// end of the program and 2) the temporary has interior mutability.const C: &AtomicU8 = &AtomicU8::new(0); // ERROR not allowed}#![allow(unused)]fn main() {use core::sync::atomic::AtomicU8;// As above.let _: &_ = const { &AtomicU8::new(0) }; // ERROR not allowed}#![allow(unused)]fn main() {#![allow(static_mut_refs)]// Even though this borrow is mutable, it's not of a temporary, so// this is allowed.const C: &u8 = unsafe { static mut S: u8 = 0; &mut S }; // OK}#![allow(unused)]fn main() {use core::sync::atomic::AtomicU8;// Even though this borrow is of a value with interior mutability,// it's not of a temporary, so this is allowed.const C: &AtomicU8 = { static S: AtomicU8 = AtomicU8::new(0); &S // OK};}#![allow(unused)]fn main() {use core::sync::atomic::AtomicU8;// This shared borrow of an interior mutable temporary is allowed// because its scope is not extended.const C: () = { _ = &AtomicU8::new(0); }; // OK}#![allow(unused)]fn main() {// Even though the borrow is mutable and the temporary lives to the// end of the program due to promotion, this is allowed because the// borrow is not in tail position and so the scope of the temporary// is not extended via temporary lifetime extension.const C: () = { let _: &'static mut [u8] = &mut []; }; // OK// ~~// Promoted temporary.}Note
In other words — to focus on what’s allowed rather than what’s not allowed — shared borrows of interior mutable data and mutable borrows are only allowed in aconst context when the borrowedplace expression istransient,indirect, orstatic.
A place expression istransient if it is a variable local to the current const context or an expression whose temporary scope is contained inside the current const context.
#![allow(unused)]fn main() {// The borrow is of a variable local to the initializer, therefore// this place expresssion is transient.const C: () = { let mut x = 0; _ = &mut x; };}#![allow(unused)]fn main() {// The borrow is of a temporary whose scope has not been extended,// therefore this place expression is transient.const C: () = { _ = &mut 0u8; };}#![allow(unused)]fn main() {// When a temporary is promoted but not lifetime extended, its// place expression is still treated as transient.const C: () = { let _: &'static mut [u8] = &mut []; };}A place expression isindirect if it is adereference expression.
#![allow(unused)]fn main() {const C: () = { _ = &mut *(&mut 0); };}A place expression isstatic if it is a
staticitem.#![allow(unused)]fn main() {#![allow(static_mut_refs)]const C: &u8 = unsafe { static mut S: u8 = 0; &mut S };}Note
One surprising consequence of these rules is that we allow this,
#![allow(unused)]fn main() {const C: &[u8] = { let x: &mut [u8] = &mut []; x }; // OK// ~~~~~~~// Empty arrays are promoted even behind mutable borrows.}but we disallow this similar code:
#![allow(unused)]fn main() {const C: &[u8] = &mut []; // ERROR// ~~~~~~~// Tail expression.}The difference between these is that, in the first, the empty array ispromoted but its scope does not undergotemporary lifetime extension, so we consider theplace expression to be transient (even though after promotion the place indeed lives to the end of the program). In the second, the scope of the empty array temporary does undergo lifetime extension, and so it is rejected due to being a mutable borrow of a lifetime-extended temporary (and therefore borrowing a non-transient place expression).
The effect is surprising because temporary lifetime extension, in this case, causes less code to compile than would without it.
Seeissue #143129 for more details.
- Thedereference operator except for raw pointers.
- Grouped expressions.
- Cast expressions, except
- pointer to address casts and
- function pointer to address casts.
- Calls ofconst functions and const methods.
Const context
Aconst context is one of the following:
- The initializer of
Const contexts that are used as parts of types (array type and repeat lengthexpressions as well as const generic arguments) can only make restricted use ofsurrounding generic parameters: such an expression must either be a single bareconst generic parameter, or an arbitrary expression not making use of anygenerics.
Const Functions
Aconst fn is a function that one is permitted to call from a const context.
Declaring a functionconst has no effect on any existing uses, it only restricts the types that arguments and thereturn type may use, and restricts the function body to constant expressions.
When called from a const context, the function is interpreted by thecompiler at compile time. The interpretation happens in theenvironment of the compilation target and not the host. Sousize is32 bits if you are compiling against a32 bit system, irrelevantof whether you are building on a64 bit or a32 bit system.