Keyboard shortcuts

Press or to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Rust constants

  • const

  • Value that can be computed during compilation.

  • Cannot be changed.

  • Must have type declaration.

  • Name must be UPPER_CASE.

#[allow(clippy::approx_constant)]
fn main() {
    const NAME: &str = "Foo";
    println!("{}", NAME);

    const PI: f64 = 3.14;
    println!("{}", PI);
    // PI = 3.1; // cannot assign to this expression

    const DAY: i32 = 60 * 60 * 24;
    println!("{}", DAY);
}
Foo
3.14
86400