2.5 Constants and Statics
2.5.1 Constants
Constants are immutable values that are set at compile time.
const MAX_POINTS: u32 = 100_000; fn main() { println!("The maximum points are: {}", MAX_POINTS); }
- Must include type annotations.
- Naming convention:
SCREAMING_SNAKE_CASE
.
2.5.2 Statics
Statics are similar to constants but represent a fixed location in memory.
static GREETING: &str = "Hello, world!"; fn main() { println!("{}", GREETING); }
2.5.3 Comparison with C
In C, you use #define
or const
for constants.
#define MAX_POINTS 100000
const int max_points = 100000;
#define
is a preprocessor directive; no type safety.const
variables can have type annotations.