RsRust
BeginnerLesson 2 of 16

Variables, Mutability & Types – Rust

let, mut, shadowing, and the most important data types.

Variables in Rust are immutable by default. Only mut allows changes. This is intentional: less mutable state means fewer bugs.

fn main() {
    let x = 5;          // immutable
    let mut y = 10;     // mutable
    y += 1;
    println!("{x} {y}");

    let x = x * 2;                  // shadowing: new variable, same name
    let x = format!("Value {x}");    // even with a different type
    println!("{x}");                // Value 10
}

Rust is statically typed but usually infers types on its own (type inference). The most important basic types:

fn main() {
    let a: i32 = -42;              // signed: i8 i16 i32 i64 i128 isize
    let b: u8 = 255;               // unsigned: u8 u16 u32 u64 u128 usize
    let c: f64 = 2.5;              // f32 or f64
    let d: bool = true;
    let e: char = '🦀';             // 4 bytes, one Unicode character
    let t: (i32, &str) = (1, "one");
    let arr: [i32; 3] = [1, 2, 3];
    const MAX_PUNKTE: u32 = 100;   // constant: type required, name in UPPERCASE
    println!("{a} {b} {c} {d} {e} {} {} {MAX_PUNKTE}", t.1, arr[0]);
}

Conversions are always explicit. You convert numbers with as and text with parse:

fn main() {
    let f = 7 as f64 / 2.0;             // 3.5
    let g = 3.9_f64 as i32;             // 3 (truncates)
    let h = 300_i32 as u8;              // 44 (wrap-around)
    let n: i32 = "42".parse().unwrap(); // text -> number
    println!("{f} {g} {h} {n}");
}
WarningInteger overflow triggers a panic in a debug build, while a release build silently wraps around. Use checked_add, wrapping_add, or saturating_add when needed.
TipFor indices and lengths, usize is the standard type. If you want to index with an i32, you have to cast.