Rustlers Atom 1.4 - Variables, binding, shadowing, mutability

Rust variables are bindings: a name tied to a value. By default, they are immutable.

Immutable vs mutable

fn main() {
    let x = 5;
    // x = 6; ❌ compile error

    let mut y = 5;
    y = 6; // ✅ works
    println!("y = {}", y);
}

The mut keyword makes intent explicit. No silent mutation is allowed in rust.

Shadowing

Instead of mutating, you can re-declare the same name.

fn main() {
    let spaces = "   ";
    let spaces = spaces.len(); // new binding, new type
    println!("spaces = {}", spaces);

Every let creates a new binding, and the old one is gone. Bindings live inside their scope. Shadowing can narrow scope deliberately.

Constants

Use const for compile-time values.

const MAX_SCORE: u32 = 100;

fn main() {
    println!("MAX_SCORE = {}", MAX_SCORE);
}

Constants require an explicit type and are always immutable. Following best practices, constants should be named using upper snake case.


You'll only receive email when they publish something new.

More from GSLF
All posts