Constants
In this page:
Declaring a Constant
Constants are declared with the const keyword, always require an explicit type, and can never be mutated. They represent values that are fixed for the entire run of the program.
Example: Declaring a Constant
const MAX_SCORE: i32 = 100;
fn main() {
println!("Maximum possible score is {}", MAX_SCORE);
}
Login to try C/C++/Java/PHP code in the editor
Naming Convention
By strong convention, Rust constants are named using SCREAMING_SNAKE_CASE -- all uppercase letters with underscores between words. This visually distinguishes constants from regular variables at a glance.
Example: Naming Convention
const SECONDS_PER_MINUTE: i32 = 60;
fn main() {
println!("A minute has {} seconds", SECONDS_PER_MINUTE);
}
Login to try C/C++/Java/PHP code in the editor
Constants at Global Scope
Unlike let bindings, constants can be declared outside of any function, at the top level of a file, making them accessible throughout the module.
Example: Constants at Global Scope
const GREETING: &str = "Welcome";
fn main() {
println!("{}, traveler!", GREETING);
}
Login to try C/C++/Java/PHP code in the editor
Constants vs Variables
Constants differ from immutable let variables in three ways: they always need a type, they can be declared in the global scope, and their value must be knowable at compile time rather than computed at runtime.
Example: Constants vs Variables
const PI_APPROX: f64 = 3.14159;
fn main() {
let radius = 2.0;
println!("Circle area: {}", PI_APPROX * radius * radius);
}
Login to try C/C++/Java/PHP code in the editor
- Using lowercase names for constants instead of Rust's convention of
SCREAMING_SNAKE_CASE. - Forgetting that constants always require an explicit type annotation, unlike
letbindings. - Trying to declare a constant with
mut-- constants can never be mutable, unlikeletvariables.
- Constants are declared with
constand must have an explicit type annotation. - Constants are always immutable -- they can never be marked
mut. - By convention, constant names use
SCREAMING_SNAKE_CASE. - Constants can be declared in any scope, including the global scope outside of
main.
Chapter Quiz — Complete all 7 topics to unlock
0/7 topics done
Complete these topics first: