</>
Skip to content
Rust lessons (9/43)

Rust — Constants

Values that never change

A constant stores a value that is fixed for the entire run of the program — things like the number of minutes in an hour.

const BIRTHYEAR: i32 = 1980;
const MINUTES_PER_HOUR: i32 = 60;

fn main() {
    println!("Born in {}", BIRTHYEAR);
}

Constants must have a type

Unlike regular variables, you must write the type when declaring a constant. The compiler won't infer it for you:

const BIRTHYEAR: i32 = 1980; // Ok
const BIRTHYEAR = 1980;      // Error: missing type

Naming convention

Write constants in UPPER_SNAKE_CASE. Not required by the compiler, but it's how every Rust codebase signals "this value never changes":

  • MAX_SPEED
  • PI
  • MINUTES_PER_HOUR

Constants vs variables

constlet
Can change later?NoYes, with mut
Type required?YesOptional (inferred)
Usable at compile time?YesNo

When to reach for a constant

Use one whenever a value has meaning and shouldn't drift. Compare:

if speed > 100 { ... }                    // what is 100?
const MAX_SPEED: i32 = 100;
if speed > MAX_SPEED { ... }              // self-documenting

Note: don't confuse const with mut. A let mut variable can change; a constant never can — and Rust will stop compilation if your code tries.

Related Topics

Frequently Asked Questions about Constants

What is Constants in Rust?

Constants is a fundamental concept in Rust. This lesson explains it step by step with clear examples, making it easy for beginners to understand.

How do I learn Constants?

Start by reading the explanation above, then try the code examples. Practice by modifying the examples and experimenting with different values. Hands-on practice is the best way to learn Constants.

Why is Constants important in Rust?

Constants is essential for Rust development. Understanding this concept will help you write better code and solve real-world problems more effectively.