Rust Constants
A constant is a value that never changes in a program. A constant value is fixed before the program starts.
Create a constant
Use const, always name the type, and write the name in SCREAMING_SNAKE_CASE. Underscores inside long numbers are ignored — they only help you read:
const MAX_POINTS: u32 = 100_000;
println!("Max points: {}", MAX_POINTS);Shadowing: the same name again
Shadowing creates a brand-new variable with the same name. The old one is hidden, not changed — and no mut is needed:
let x = 5;
let x = x + 1;
println!("x = {}", x);Shadowing can change the type
The new variable may even hold a different type. Here the text " " becomes its own length — a number:
let spaces = " ";
let spaces = spaces.len();
println!("spaces = {}", spaces);Example
const MAX_POINTS: u32 = 100_000;
fn main() {
let x = 5;
let x = x + 1; // shadowed: now 6
{
let x = x * 2; // shadowed again, only in this scope
println!("Inner x: {}", x);
}
println!("Outer x: {}", x);
println!("Max points: {}", MAX_POINTS);
}Key points
- The value must be knowable at compile time — simple maths with known values is fine
- Use const fn to write a small function that Rust can run at compile time
- Any function can read a global const directly.
- There is no need to pass it in.
- A helper like is_big can test n > THRESHOLD on its own.
- A static also always names its type, just like const.
- Its 'static lifetime is worked out by Rust.
- So you never write it.
- An array length may come from a const, like [7u8; DIGEST_SIZE].
- A const is a fixed value known while compiling.
- That is exactly what an array length must be.
In this example, MAX_POINTS is declared at the top of the file. It sits outside any function. So the whole program can use it. Inside main, x starts at 5. The second let shadows it: the new x is the old value + 1, so 6. The block in braces shadows x once more, only inside that block. Inside it, x * 2 is 12. That is the Inner x that prints. When the block ends, the inner x is gone, and the outer x is still 6. The last line prints the constant itself: 100000.
Note
Unlike a variable, a constant is copied into each place that uses it.
It has no single home in memory.
A static item does have one fixed home — use const unless you need that.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Rust Playground
Exercise
Which of these values can be a const?