liveBook · Manning

Associated constant

As explained in Learn Rust in a Month of Lunches

An associated constant is a constant value defined within a Rust type or trait and accessed through that type or trait.

An associated constant is a constant value defined on a Rust type or trait and accessed with the type’s name and :: syntax. Define one inside an impl block with const NAME: Type = value. section 20.5.3 section 20.10

A constant on a type

struct SizeTenString(String); impl SizeTenString { const SIZE: usize = 10; } fn main() { println!("{}", SizeTenString::SIZE); } The constant can also support validation: compare an input’s character count with Self::SIZE, then return the value or an error when the length is wrong.

Traits can declare associated constants as defaults or requirements. An implementation must provide a required constant and may override a default one, allowing each type to choose its value. section 20.5.3

Default and required trait constants

trait HasNumbers { const SET_NUMBER: usize = 10; const EXTRA_NUMBER: usize; } struct NothingSpecial; impl HasNumbers for NothingSpecial { const EXTRA_NUMBER: usize = 10; } NothingSpecial::SET_NUMBER uses the default value 10, while EXTRA_NUMBER is supplied by the implementation. Uncommenting an override can change the default to 20.

Associated constants are one of Rust’s three associated items, alongside associated functions and associated types. Standard-library types expose examples such as f32::MIN, f64::MAX, INFINITY, EPSILON, and DIGITS. section 20.10 section 20.4

How Learn Rust in a Month of Lunches covers it

How deep it goes
Explains declaration, :: access, trait defaults, required values, overrides, and validation, but does not explore constant evaluation internals.
Examples
Demonstrates SizeTenString::SIZE, length validation through Self::SIZE, trait defaults and requirements, and float constants such as MIN and MAX.
What it assumes
Assumes basic Rust types and traits while introducing associated items and their relationship to functions, types, and constants.
What you can do after
Build it from scratch by declaring associated constants on types and traits, accessing them with ::, and overriding trait defaults.
How it connects
Connects associated constants with impl blocks, traits, associated functions, associated types, and standard-library types.

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.