Variables and Constants

Rust by example - Variable bindings Rust by example - constants


fn main() {
    // `const` is set to a constant expression; the type must be annotated
    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

    let apples = 5; // immutable variable

    let mut guess = String::new(); // mutable variable
}

Shadowing

fn main() {
    let x = 5; // x is immutable

    let x = x + 1; // redefines x
    println!("{x}");

    let x = "example"; // the type can change
    println!("{x}");
}

Destructuring

fn main() {
    // destructuring tuples
    let (_x, _y, _z) = (1, 2, 3);

    // destructuring structs
    struct Point {
        x: i32,
        y: i32,
    }

    let p = Point { x: 0, y: 7 };
    let Point { x: _a, y: _b } = p; // a = 0, b = 7
    let Point { x, y } = p; // simpler
    let _ = (x, y);
}

Starting the name of a variable with an underscore silences unused variable warnings.