← Back to Rust Course | Chapter 2: Variables & Types | Lesson 3 of 7

Constants

A constant is a value that gets a permanent name and can never, ever be changed while the program runs.

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

markup
const MAX_SCORE: i32 = 100;

fn main() {
    println!("Maximum possible score is {}", MAX_SCORE);
}

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

markup
const SECONDS_PER_MINUTE: i32 = 60;

fn main() {
    println!("A minute has {} seconds", SECONDS_PER_MINUTE);
}

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

markup
const GREETING: &str = "Welcome";

fn main() {
    println!("{}, traveler!", GREETING);
}

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

markup
const PI_APPROX: f64 = 3.14159;

fn main() {
    let radius = 2.0;
    println!("Circle area: {}", PI_APPROX * radius * radius);
}
Common Mistakes
  1. Using lowercase names for constants instead of Rust's convention of SCREAMING_SNAKE_CASE.
  2. Forgetting that constants always require an explicit type annotation, unlike let bindings.
  3. Trying to declare a constant with mut -- constants can never be mutable, unlike let variables.
Chapter Summary
  • Constants are declared with const and 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:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.