Constants
In this page:
const NAME: Type = value;
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;
// Entry point: execution of the program starts here
fn main() {
// Print "Maximum possible score is {}" to the console, substituting in `MAX_SCORE` (with a trailing newline)
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;
// Entry point: execution of the program starts here
fn main() {
// Print "A minute has {} seconds" to the console, substituting in `SECONDS_PER_MINUTE` (with a trailing newline)
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";
// Entry point: execution of the program starts here
fn main() {
// Print "{}, traveler!" to the console, substituting in `GREETING` (with a trailing newline)
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;
// Entry point: execution of the program starts here
fn main() {
// Declare an immutable variable `radius`, set to `2.0`
let radius = 2.0;
// Print "Circle area: {}" to the console, substituting in `PI_APPROX * radius * radius` (with a trailing newline)
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: