From Rust Community Wiki
Jump to navigation Jump to search

See also: Reference – Constant items

A constant is an item that is const-evaluated at compile time and inlined at every usage site. Unlike static variables, constants don't have a fixed memory location; therefore, references to the same constant can point to different memory locations.

Constants must be explicitly typed and have a 'static lifetime:

const FOO: i32 = 5 << 3 + 2;

fn foo() -> i32 {

Since constants are evaluated and inlined at compile time, the above is semantically equivalent to

fn foo() -> i32 {

Constants can have a destructor, which is run when the constant goes out of scope.

It is possible to create unnamed constants, which use the underscore (_) instead of a name:

const _: i32 = 42;
const _: bool = !true;