liveBook · Manning

Const qualifier

As explained in Learn Rust in a Month of Lunches

A language feature that marks a value, binding, or access path as constant, restricting reassignment or modification according to the language’s rules.

In Rust, const declares an unchangeable value created at compile time. Unlike ordinary let bindings, const requires an explicit type and is commonly written in capital letters outside main. section 2.3

Use const when a value should remain available throughout the program:

  • Write the type explicitly because Rust does not infer const types. section 2.3
  • Define compile-time values such as NUMBER_OF_MONTHS or an allowed-character string. section 2.3 section 14.3.1
  • Access a const from different functions without passing it as an argument or managing ownership. section 2.3
  • Remember that compile-time requirements prevent values needing heap allocation or unknown-at-compile-time data from becoming const. section 2.3

A constant used for input validation

const OKAY_CHARACTERS: &str = "1234567890- "; An input checker can iterate over the characters in OKAY_CHARACTERS and reject any character that does not belong to it. The constant keeps the accepted input rule in one unchangeable, reusable value. section 14.3.1

const NUMBER_OF_MONTHS: u32 = 12;
static SEASONS: [&str; 4] = ["Spring", "Summer", "Fall", "Winter"];

Compare a const declaration with a static declaration and see the required type annotations and capitalized names. section 2.3

How Learn Rust in a Month of Lunches covers it

How deep it goes
Defines declarations, typing, scope, and compile-time limits, while deferring deeper const-versus-static details.
Examples
Demonstrates numeric bounds, month counts, seasons, and calculator input validation with named constants.
What it assumes
Assumes basic Rust values and functions while teaching const declarations, explicit types, scope, and compile-time restrictions.
What you can do after
Apply it by declaring typed compile-time values and reusing them across functions or validation logic.
How it connects
Connects const with static, compile-time evaluation, type annotations, global variables, ownership, and references.

Also explained in

Compare how 7 books explain const qualifier →

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.