TExcelTAD
Home › Rust › Rust Constants

Rust Constants

Some values never change while a program runs: the number of days in a week, a maximum file size, the speed of light. Rust lets you give such values a name with the const keyword. A constant is fixed forever — there is no way to make it mutable.

Declaring a constant

rust · try it yourself
const DAYS_IN_WEEK: u32 = 7;
const HOURS_IN_DAY: u32 = 24;

fn main() {
    let hours_in_week = DAYS_IN_WEEK * HOURS_IN_DAY;
    println!("A week has {} hours.", hours_in_week);
}
A week has 168 hours.

Three rules apply to every constant:

  1. You must write the type (: u32). Rust does not infer types for constants.
  2. The name is written in SCREAMING_SNAKE_CASE by convention.
  3. The value must be known at compile time. You can use literals, arithmetic and other constants, but not values that only exist while the program runs.

Constants vs. variables

let let mut const
Can change? No Yes Never
Type annotation Optional Optional Required
Value computed At run time At run time At compile time
Allowed at the top of a file (global)? No No Yes
Can be shadowed? Yes Yes No

Because constants are allowed outside of functions, they are a natural place for settings that many functions share.

Constants built from other constants

A constant's value may be any expression the compiler can evaluate on its own, including arithmetic on other constants:

rust · try it yourself
const SECONDS_PER_MINUTE: u64 = 60;
const MINUTES_PER_HOUR: u64 = 60;
const SECONDS_PER_HOUR: u64 = SECONDS_PER_MINUTE * MINUTES_PER_HOUR;
const SECONDS_PER_DAY: u64 = SECONDS_PER_HOUR * 24;

fn main() {
    println!("One hour  = {} seconds", SECONDS_PER_HOUR);
    println!("One day   = {} seconds", SECONDS_PER_DAY);
    println!("One year  = {} seconds", SECONDS_PER_DAY * 365);
}
One hour  = 3600 seconds
One day   = 86400 seconds
One year  = 31536000 seconds

The calculations happen while compiling, so they cost nothing when the program runs.

Using constants in functions

Constants are visible everywhere in the module where they are defined, so any function can use them:

rust · try it yourself
const TAX_RATE: f64 = 0.2;
const SHOP_NAME: &str = "Corner Books";

fn price_with_tax(net: f64) -> f64 {
    net * (1.0 + TAX_RATE)
}

fn main() {
    println!("Welcome to {}!", SHOP_NAME);
    println!("A 15.00 book costs {:.2} with tax.", price_with_tax(15.0));
    println!("A 8.50 book costs {:.2} with tax.", price_with_tax(8.5));
}
Welcome to Corner Books!
A 15.00 book costs 18.00 with tax.
A 8.50 book costs 10.20 with tax.

If the tax rate changes, you edit one line instead of hunting through the whole program for the number 0.2. Unnamed numbers scattered through code are often called magic numbers; replacing them with named constants is one of the easiest ways to make code clearer.

Constants cannot be changed

Trying to assign to a constant fails at compile time:

rust
const LIMIT: i32 = 10;

fn main() {
    LIMIT = 20;
}
text
error[E0070]: invalid left-hand side of assignment
 --> src/main.rs:4:11
  |
4 |     LIMIT = 20;
  |     ----- ^
  |     |
  |     cannot assign to this expression

Using let inside the program instead is also not possible for global values — let only works inside functions.

A note on static

Rust has a second keyword for global values, static:

rust
static GREETING: &str = "Hello";

The difference is subtle: a const is copied into every place it is used, while a static lives at one fixed memory address for the whole program. For ordinary fixed values like numbers and short strings, prefer const.

Tip: Put your constants at the top of the file, right after any use lines. Readers then see all the important settings of the program at a glance.

Test yourself

Which of these is a valid constant declaration?

  1. const max = 10;
  2. const MAX = 10;
  3. const MAX: i32 = 10;
  4. let const MAX = 10;

When is the value of a const computed?

  1. At compile time
  2. When main starts
  3. The first time it is used
  4. Every time it is used

Which naming style do Rust constants use?

  1. snake_case
  2. camelCase
  3. SCREAMING_SNAKE_CASE
  4. UpperCamelCase