Constants and shadowing
Quick answer
A const names a compile-time constant and requires an explicit type. Shadowing introduces a new binding with the same name using another let. Unlike reassignment, shadowing can introduce a different type.
Distinguish three operations
A constant may be used wherever it is in scope and its initializer must be a permitted constant expression. An immutable local binding is not necessarily a compile-time constant. A mutable binding changes its current value; shadowing creates a new binding that hides the earlier name within its scope.
const SEATS_PER_ROW: u32 = 6;fn main() { let rows = 4; println!("Seats: {}", rows * SEATS_PER_ROW);}Expected stdout (not executed):
Seats: 24Uppercase names with underscores are the customary constant naming style.
fn main() { let amount = 5; let amount = amount + 2; println!("{amount}"); let amount = "seven"; println!("{amount}");}Expected stdout (not executed):
7sevenThe third binding has a different type; the earlier binding is hidden.
Common mistake
Do not use const for a value that depends on runtime user input. Writing a new let is different from assigning to an existing mutable binding.
Try it yourself
Define a constant for minutes per hour, then shadow a binding called hours with its calculated minute count.
Static examples for Rust 1.85.0, edition 2024. Run them locally in a disposable project; ByteMind execution support and these outputs have not been verified.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Constants and shadowing — practice quiz
Choose one answer per question, then review the explanation.
Which constant declaration supplies the required type?
What does `let price = 3; let price = price * 4;` do?
Are all immutable local let bindings compile-time constants?