RS Rust

Rust: Variables & Types

What you will learn

Rust is statically typed with a powerful type-inference system. Variables are immutable by default -- one of Rust's core safety features.

Declaring variables

let name = "Alice";     // &str (string slice)
let age: u32 = 25;       // explicit type annotation
let height = 5.6;        // f64 (inferred)
let is_student = true;   // bool

The let keyword creates a binding. By default, bindings are immutable -- you cannot reassign them:

let x = 5;
// x = 6;  // compile error -- cannot assign twice to immutable

Mutability

Add mut to make a binding mutable:

let mut y = 5;
y = 6;  // OK

Type inference

Rust infers types from usage. You only need annotations when inference is ambiguous:

let guess: u32 = "42".parse().expect("not a number");
                // parse() needs a hint -- we give it with : u32

Shadowing

You can declare a new variable with the same name as an earlier one -- the new one shadows the old:

let x = 5;
let x = x + 1;  // shadow: x is now 6
let x = "now a string";  // can even change type

This is different from mut -- shadowing creates a new binding; the old one is gone.

Common mistakes

  • Forgetting mut and getting a compile error instead of understanding Rust's safety model
  • Expecting integer division to round: 5 / 2 in Rust gives 2 (integer truncation) -- use 5.0 / 2.0 for 2.5
  • Using let when you meant const -- const is for compile-time constants, let is for runtime values

Quick check below!