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






