Beginner Fundamentals

Constants

Constants hold values that never change. Unlike variables, they require an explicit type annotation and can be declared in any scope, including the global scope.

const

Use const for values fixed at compile time. By convention, names use uppercase with underscores.

const MAX_USERS: u32 = 1000;

fn main() {
    println!("Max users: {}", MAX_USERS);
}

A const has no fixed memory address; the compiler inlines its value wherever it is used.

Type annotation is required

You cannot let Rust infer a constant’s type. This is mandatory:

const PI: f64 = 3.14159; // type f64 must be written

Leaving out : f64 would be a compile error.

static

A static is similar but represents a single value with a fixed memory location that lives for the entire program.

static GREETING: &str = "Welcome";

fn main() {
    println!("{}", GREETING);
}

const vs static

  • const: inlined value, no fixed address, use for plain constants.
  • static: single instance with a fixed address, use when an address matters.

Prefer const unless you specifically need a static.