Variables and mut

View saved

Immutable by default

Bindings cannot change unless you mark them mut.

fn main() {
    let x = 5;
    println!("{x}");
    // x = 6; // does not compile
}

Make a binding mutable

Add mut when you intentionally reassign or mutate.

let mut count = 0;
count += 1;
println!("{count}");

Shadowing

You can declare a new let with the same name to transform a value without mutability.

let spaces = "   ";
let spaces = spaces.len();
println!("{spaces}");

Types you will use first

  • Integers: i32 (common default), u8, usize
  • Floating point: f64
  • Booleans: bool
  • Text: &str string slices and owned String

Comments

One comment per signed-in account. Comments are saved with this page’s URL.