GGistDev

Variables in Rust

Bindings control mutability and lifetimes. Rust defaults to immutability; opt into mutability with mut.

let and mut

let x = 1;        // immutable
let mut y = 0;    // mutable
y += 1;

Shadowing

Rebind the same name to a new value/type; useful for transformations.

let s = "  hello  ";
let s = s.trim();
let s = s.len();   // now usize

Destructuring patterns

Unpack tuples/structs in let bindings.

let (a, b) = (1, 2);
struct Point { x: i32, y: i32 }
let p = Point { x: 1, y: 2 };
let Point { x, y } = p;

Scope and shadow lifetimes

Blocks create new scopes; shadowed names drop when they go out of scope.

let x = 1;
{
    let x = 2; // shadows outer x
    assert_eq!(x, 2);
}
assert_eq!(x, 1);

Constants and statics (preview)

const and static define global bindings (see Constants section).

Naming and style

Use snake_case for variables and constants; prefer explicit names over abbreviations.

Summary

  • Default to immutable; use mut when mutation is needed
  • Shadowing enables stepwise transforms; patterns unpack values