Rust has a way of defining constants with the const
`const` keyword:
const N: i32 = 5;
Unlike let
`let` bindings, you must annotate the type of a const
`const`.
Constants live for the entire lifetime of a program. More specifically, constants in Rust have no fixed address in memory. This is because they’re effectively inlined to each place that they’re used. References to the same constant are not necessarily guaranteed to refer to the same memory address for this reason.
static
`static`Rust provides a ‘global variable’ sort of facility in static items. They’re similar to constants, but static items aren’t inlined upon use. This means that there is only one instance for each value, and it’s at a fixed location in memory.
Here’s an example:
fn main() { static N: i32 = 5; }static N: i32 = 5;
Unlike let
`let` bindings, you must annotate the type of a static
`static`.
Statics live for the entire lifetime of a program, and therefore any
reference stored in a constant has a ’static
`’static` lifetime:
static NAME: &'static str = "Steve";
You can introduce mutability with the mut
`mut` keyword:
static mut N: i32 = 5;
Because this is mutable, one thread could be updating N
`Nwhile another is reading it, causing memory unsafety. As such both accessing and mutating a
` while another is
reading it, causing memory unsafety. As such both accessing and mutating a
static mut
`static mutis [
` is unsafe
`unsafe`, and so must be done in an unsafe
`unsafe` block:
unsafe { N += 1; println!("N: {}", N); }
Furthermore, any type stored in a static
`staticmust be
` must be Sync
`Sync`.
Both const
`constand
` and static
`static` have requirements for giving them a value. They may
only be given a value that’s a constant expression. In other words, you cannot
use the result of a function call or anything similarly complex or at runtime.
Almost always, if you can choose between the two, choose const
`const`. It’s pretty
rare that you actually want a memory location associated with your constant,
and using a const allows for optimizations like constant propagation not only
in your crate but downstream crates.
A const can be thought of as a #define
`#define` in C: it has metadata overhead but it
has no runtime overhead. “Should I use a #define or a static in C,” is largely
the same question as whether you should use a const or a static in Rust.