Skip to main content

Shadowing, const and static

Shadowing declares a brand new binding that happens to reuse a name. Unlike `mut`, it can change the type — which is exactly what you want when parsing input into a number, or trimming a string.

`const` is a compile-time value that gets inlined wherever it is used. It always needs a written type and it can live anywhere, including inside a function.

`static` is a single value with a fixed memory address for the whole run of the program. Reach for `const` unless you specifically need that address or a genuinely global buffer.

Trying to change a type with mut

fn main() {
    let mut value = "42";
    value = 42; // error[E0308]
}

error[E0308]: mismatched types: expected `&str`, found integer

`mut` lets the value change, not the type. Shadow instead: `let value: i32 = value.parse().unwrap();`

Run it and change it

The editor below is live: edit anything and the real compiler output updates by itself.

Your Rust