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;
    // ERROR: THREE_HOURS_IN_SECONDS = 10800;

    // Immutable variable
    let apples = 5;
    // ERROR: apples = 6;
    println!("apples: {}", apples);

    // Mutable variable
    let mut guess = String::new();
    guess.push_str("42");
    println!("guess: {}", guess);
}

Shadowing

fn main() {
    // `x` is an immutable variable
    let x = 5;
    // ERROR: x = x +1;

    // But it can be redefined:
    let x = x + 1;
    println!("{x}");

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

Destructuring

fn main() {
    // Destructuring a tuple
    let (x, y, _) = (1, 2, 3);
    // x, y are now stored individually in two separate `i32` variables
    // Use _ to ignore a field you don't care about.
    println!("x: {x}, y: {y}");

    struct Point {
        x: i32,
        y: i32,
    }

    let p = Point { x: 0, y: 7 };
    // Destructuring a struct - sets a = 0 and b = 7:
    let Point { x: a, y: b } = p;
    println!("a: {a}, b: {b}");

    // Here is a simpler way:
    let Point { x, y } = p;
    // This is equivalent to `let Point { x: x, y: y } = p;``
    print!("x and y: {:?}", (x, y));
    // An underscore can be used as well, if needed.
}

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