2.6 Constants and Statics
Rust provides constants for values known at compile time and statics for immutable global data. Constants remain unchanged throughout execution and must have an explicitly declared type. Unlike variables, they do not occupy a specific memory location and can be freely copied or optimized by the compiler.
Statics, on the other hand, represent values stored at a fixed memory address. They are initialized once at runtime and remain available throughout the program’s execution.
2.6.1 Constants
By convention, constant names are written in SCREAMING_SNAKE_CASE
:
const MAX_POINTS: u32 = 100_000; fn main() { println!("The maximum points are: {}", MAX_POINTS); }
2.6.2 Statics
Statics differ from constants in that they have a fixed memory location:
static GREETING: &str = "Hello, world!"; fn main() { println!("{}", GREETING); }
Mutable statics are generally discouraged in Rust because modifying global data can introduce race conditions. If mutability is required, it must be wrapped in synchronization primitives (such as Mutex
or Atomic*
types), and access to it requires unsafe
code.
2.6.3 Comparison with C
#define MAX_POINTS 100000
const int max_points = 100000;
#define
is a preprocessor directive and does not enforce type safety.const
in C applies type safety but does not necessarily guarantee immutability at the machine level.- In Rust,
const
ensures compile-time evaluation and optimization, whilestatic
provides a persistent memory location.