What is the difference between a const variable and a static variable and which should I choose?
Mutability
A const
variable in Rust is immutable. You neither can reassign nor modify it:
struct Foo(u32);
const FOO: Foo = Foo(5);
fn main() {
FOO = Foo(1); //illegal
FOO.0 = 2; //illegal
}
A static
variable can be mutable and therefore can either be modified or reassigned. Note that writing/modifying a global static
variable is unsafe and therefore needs an unsafe
block:
struct Foo(u32);
static FOO: Foo = Foo(5);
static mut FOO_MUT: Foo = Foo(3);
fn main() {
unsafe {
FOO = Foo(1); //illegal
FOO.0 = 2; //illegal
FOO_MUT = Foo(1);
FOO_MUT.0 = 2;
}
}
Occurrences
When you compile a binary, all const
"occurrences" (where you use that const
in your source code) will be replaced by that value directly.
static
s will have a dedicated section in your binary where they will be placed (the BSS section, see Where are static variables stored in C and C++? for further information).
All in all, stick to a const
whenever possible. When not possible, because you need to initialize a variable later in the program of with non-const
methods, use lazy_static!
.
There's not much practical difference if your variable isn't intended to change.
Constants are inlined at compilation, which means they're copied to every location they're used, and thus are usually more efficient, while statics refer to a unique location in memory and are more like global variables.
Constants are... constant while statics, while still global, can be mutable.