liveBook · Manning

Const variable

As explained in Learn Rust in a Month of Lunches

A const variable is a binding whose value cannot be reassigned after declaration.

In Rust, `const` declares an unchanging value evaluated at compile time. Each constant needs an explicit type annotation. section 2.3

A const is useful when a value is known before the program runs:

  • Constants are conventionally written in uppercase and often declared outside `main` so they can be accessed throughout the program. section 2.3
  • A const can hold a set of allowed input characters, which code can check against. section 14.3.1
const NUMBER_OF_MONTHS: u32 = 12;
 
fn print_months() {                       #1
    println!("Number of months in the year: {NUMBER_OF_MONTHS}");
}
 
fn main() {
    print_months();
}

This example declares a typed constant outside `main` and reads it inside another function. section 2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains type annotations, compile-time evaluation, and global access, then develops the distinction from `static` later.
Examples
Uses NUMBER_OF_MONTHS, SEASONS, integer MIN and MAX values, and calculator input characters.
What you can do after
Build from scratch by declaring a typed compile-time value and accessing it from another function.
How it connects
Connects const with static, type annotations, compile-time evaluation, and global values.

Also explained in

Compare how 8 books explain const variable →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Learn Rust in a Month of Lunches. The section links point to the parts of the book it draws on.