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
