Rust Constants
Some values in a program are fixed facts: the number of days in a week, the pass mark of an exam, the speed of light, the tax rate your shop uses. For values like these, Rust has constants. A constant is a name for a value that never changes while the program runs, and that is known before the program even starts.
You create one with the word const. Two rules are different from let: you must always write the type, and the name is written in capital letters with underscores, which tells every reader at a glance that this is a constant.
const DAYS_IN_WEEK: u32 = 7;
const PASS_MARK: u32 = 40;
fn main() {
let weeks = 6;
println!("{} weeks is {} days", weeks, weeks * DAYS_IN_WEEK);
let marks = 52;
println!("Passed: {}", marks >= PASS_MARK);
}6 weeks is 42 days Passed: true
Why not just use let?
You could write let pass_mark = 40; inside main and the program would work. Constants still have real advantages:
- They live outside functions. A constant written at the top of the file can be used in every function of the program, so a value like the pass mark is defined in one place only.
- One change updates everything. If the pass mark becomes 35 next year, you change one line instead of hunting through the code for every 40.
- They explain themselves.
marks >= PASS_MARKtells a story;marks >= 40leaves the reader wondering where 40 came from. Programmers call such unexplained numbers magic numbers, and constants are the cure.
Constants with calculations
A constant's value can be a calculation, as long as Rust can work it out while compiling:
const SECONDS_PER_MINUTE: u64 = 60;
const SECONDS_PER_HOUR: u64 = 60 * SECONDS_PER_MINUTE;
const SECONDS_PER_DAY: u64 = 24 * SECONDS_PER_HOUR;
fn main() {
println!("One hour has {} seconds", SECONDS_PER_HOUR);
println!("One day has {} seconds", SECONDS_PER_DAY);
}One hour has 3600 seconds One day has 86400 seconds
Something that can only be known while the program runs, such as a number the user types, cannot be a constant. For those, use let.
Rust also has static, which looks similar but is a single fixed place in memory. Beginners rarely need it; const is the one to reach for.
Practice exercises
- Create a constant
GST_RATE: f64 = 0.18and use it to print the tax on a price of 250.0. - Make constants for minutes in an hour and hours in a day, and print the minutes in a week.
- Try to change a constant with
PASS_MARK = 35;insidemainand read the error.