Variables and Constants

Rust by example - Variable bindings Rust by example - constants

/// Variables and constants are used to store values.
/// Variables can be mutable or immutable.
/// Constants are always immutable.
fn main() {
    // Constants are always immutable.
    // The type must be provided.
    // Here, `const` is set to a constant expression.
    const THREE_HOURS_IN_SECONDS: u32 = 60 * 60 * 3;

    // Immutable variable:
    let apples = 5;
    // You cannot reassign an immutable variable.
    // ERROR: apples = 6;
    println!("apples: {}", apples);

    // Mutable variable - note the `mut` keyword.
    let mut guess = String::new();
    // You can modify a mutable variable.
    guess.push_str("42");
    println!("guess: {}", guess);
}

Shadowing

fn main() {
    // `x` is an immutable variable.
    let x = 5;
    // ERROR: x = x +1; // This would be an error because `x` is immutable.

    // But it can be redefined (shadowed). Notice the `let`.
    let x = x + 1;
    // The new `x` is a new variable that shadows the previous one.
    println!("{x}");

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

Destructuring

fn main() {
    // Destructuring a tuple.
    // The values in the tuple are assigned to the variables in the same order.
    let (x, y, _) = (1, 2, 3);
    // x is assigned the value 1.
    // y is assigned the value 2.
    // Use `_` to ignore a field you don't care about.

    println!("x: {x}, y: {y}");

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

    // Create a `struct` instance.
    let p = Point { x: 0, y: 7 };

    // Destructuring a struct.
    // The values in the struct are assigned to the variables based on the field
    // names. a is assigned the value of p.x, which is 0.
    // b is assigned the value of p.y, which is 7.
    let Point { x: a, y: b } = p;
    println!("a: {a}, b: {b}");

    // Here is a simpler way to destructure a struct.
    let Point { x, y } = p;
    // This is equivalent to `let Point { x: x, y: y } = p;`.
    print!("x and y: {:?}", (x, y));
}

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