Skip to content
RustLearn

Module 02 — Variables, Types & Memory Basics

Goal

Immutability by default, shadowing, constants, the scalar and compound types, and your first real look at the stack and the heap.

Start here — what this module is really about

This module is about two questions other languages barely ask you: can this value be changed? and where does it physically live?

On the first: in most languages a variable is a box you can overwrite whenever you like, and you have to opt in to protection with something like const or final. Rust reverses the default. Write let x = 5; and x can never be reassigned. If you want to change it, you say so explicitly with let mut x = 5;. This sounds like a small stylistic choice; it is actually the foundation of modules 04 and 05, because the compiler can only make promises about data that cannot change behind its back.

On the second: your program has two places to put data.

  • The stack is fast, ordered scratch space. Values there must have a size the compiler knows in advance — a number, a character, a fixed-length group of them. They are created and destroyed in strict order as your functions run.
  • The heap is a large, flexible area for things whose size is only known while the program runs, or that must outlive the function that made them. Getting space there costs a little time, and something has to decide when to give it back.

You do not manage this by hand in Rust. But you do need to know which one a value is in, because that single fact decides whether assigning it copies it or moves it — which is the whole of module 04.

The one sentence to remember: values are fixed unless you say otherwise, and small fixed-size things live on the stack while growable things live on the heap.

Learning objectives

  • Explain why Rust bindings are immutable by default and when to reach for mut
  • Use shadowing deliberately, and distinguish it from mutation
  • Choose between const and static
  • Know every scalar type, its size, and its overflow behaviour
  • Use tuples and arrays, and understand why arrays have a fixed length
  • Describe the stack and the heap well enough to survive module 04

2.1 Bindings, not variables

rust
fn main() {
    let x = 5;
    // x = 6;  // ❌ error[E0384]: cannot assign twice to immutable variable `x`

    let mut y = 5;
    y = 6;      // ✅
    println!("{x} {y}");
}

The error message is worth reading:

error[E0384]: cannot assign twice to immutable variable `x`
  |
2 |     let x = 5;
  |         - first assignment to `x`
3 |     x = 6;
  |     ^^^^^ cannot assign twice to immutable variable
  |
help: consider making this binding mutable: `let mut x = 5;`

Why immutability is the default

  1. Concurrency. Immutable data can be shared across threads freely; mutable data cannot. Making the safe case the default makes the dangerous case visible.
  2. Reasoning. If a binding is not mut, you know its value can never change, no matter how far away the code is.
  3. Optimization. The compiler exploits immutability aggressively.

mut is not a code smell. Reach for it when the value genuinely changes over time. But when you find yourself writing let mut and then assigning once, prefer restructuring:

rust
// ❌ awkward
let mut label = String::new();
if score > 50 { label = "pass".to_string(); } else { label = "fail".to_string(); }

// ✅ if is an expression
let label = if score > 50 { "pass" } else { "fail" };

TS ↔ Rust: let in Rust ≈ const in JS. let mut in Rust ≈ let in JS. But note JS's const only freezes the binding; Rust's immutability is deep — you cannot mutate through an immutable binding at all.


Analogy — ink, not pencil

In most languages a variable is a whiteboard: write, wipe, write again, and anyone in the room can change it while your back is turned. In Rust the default is ink on a signed form — the value stands unless you explicitly asked for a form that may be amended (mut). Most of what you write never needs amending, and the compiler quietly proves it for you.

2.2 Shadowing

Shadowing declares a new binding that reuses a name:

rust
fn main() {
    let x = 5;
    let x = x + 1;         // 6  — new binding
    let x = x * 2;         // 12 — new binding again

    {
        let x = "inner";   // shadows only inside this block
        println!("{x}");   // inner
    }
    println!("{x}");       // 12
}

Shadowing vs mutation — the difference that matters:

let mut x = 5; x = 6;let x = 5; let x = 6;
Same memory slot?YesNo, a new one
Can change type?❌ no✅ yes
Value mutable afterward?YesNo
rust
let spaces = "   ";
let spaces = spaces.len();   // ✅ &str -> usize, type changed

let mut spaces = "   ";
// spaces = spaces.len();    // ❌ E0308: expected `&str`, found `usize`

Idiomatic use: parsing and normalizing input while keeping one obvious name.

rust
let input = "  42  ";
let input = input.trim();               // &str
let input: u32 = input.parse().unwrap(); // u32

Gotcha

Shadowing in a loop body creates a new binding each iteration; it does not carry values between iterations. If you need accumulation, declare let mut outside the loop.


Shadowing vs. mut — the distinction people get wrong

These two look similar and are not the same thing:

rust
let mut x = 5;
x = 6;              // mutation: same box, new contents

let y = 5;
let y = y + 1;      // shadowing: a brand-new box that happens to reuse the name

Why it matters in practice:

  • Mutation cannot change the type. x was a number and stays a number forever. Assigning text to it is an error.
  • Shadowing can. let spaces = " "; let spaces = spaces.len(); starts as text and ends as a number, and that is fine — the second spaces is a different value that merely reuses the name.
  • Shadowing keeps immutability. After let y = y + 1;, y still cannot be reassigned. You have not made anything changeable; you have made a new fixed value.

The idiomatic use is exactly that last case: transforming a value through a few steps without inventing input_raw, input_trimmed, input_parsed, and without making anything mutable.

Analogy — a new page, same title

Shadowing is not editing the form; it is starting a fresh page under the same heading, and the old page is filed away. That is why the type may change — the new page is a different form entirely — and why the old value still exists safely underneath in the enclosing scope.

2.3 Constants and statics

rust
const MAX_USERS: u32 = 100_000;                 // inlined at every use site
static GREETING: &str = "hello";                // one fixed memory location
static mut COUNTER: u32 = 0;                    // requires `unsafe` to touch — avoid
conststatic
Type annotationrequiredrequired
Memoryinlined, no fixed addresssingle fixed address, 'static lifetime
Mutable?neveronly with unsafe (don't)
Scopeany, including inside fnany
Use formagic numbers, limits, conversionslarge data, globals needing an address

Naming convention is SCREAMING_SNAKE_CASE. Constants can be computed from const expressions:

rust
const SECONDS_PER_DAY: u32 = 60 * 60 * 24;
const BUFFER: usize = 1 << 12;

Default to const. Reach for static only when you need a stable address or the data is large. For mutable global state, use std::sync::OnceLock, LazyLock, or a Mutex — never static mut.

2.4 Scalar types

Integers

LengthSignedUnsigned
8-biti8u8
16-biti16u16
32-biti32 (default)u32
64-biti64u64
128-biti128u128
pointer-sizedisizeusize

usize is the type of indexes and lengths — 64 bits on a 64-bit machine.

Literals:

rust
let dec = 98_222;      // underscores are visual separators
let hex = 0xff;
let oct = 0o77;
let bin = 0b1111_0000;
let byte = b'A';       // u8 only, = 65
let typed = 42u8;      // suffixed literal
let annotated: i64 = 42;

Integer overflow — the thing that surprises everyone

rust
let x: u8 = 255;
let y = x + 1;
  • Debug build: panics at runtime — attempt to add with overflow.
  • Release build: wraps silently to 0 (two's complement wrapping).

This asymmetry exists so you catch bugs in development without paying for checks in production. When wrapping (or saturating) is what you actually want, say so explicitly:

rust
let a: u8 = 255;
a.wrapping_add(1);       // 0        — wrap around
a.checked_add(1);        // None     — Option<u8>, safest
a.saturating_add(1);     // 255      — clamp at the max
a.overflowing_add(1);    // (0, true) — value plus a "did it overflow" flag

Rule of thumb

If a value comes from user input or arithmetic that could exceed the type, use checked_* and handle the None.

Floating point

rust
let x = 2.0;        // f64 by default
let y: f32 = 3.0;

f64 is the default and is usually just as fast on modern hardware. Floats obey IEEE-754, which means:

rust
assert!(0.1 + 0.2 != 0.3);            // classic float trap
assert!((0.1f64 + 0.2 - 0.3).abs() < f64::EPSILON);  // compare with a tolerance
let nan = f64::NAN;
assert!(nan != nan);                   // NaN is not equal to itself

Because of NaN, floats implement PartialOrd but not Ord, which means you cannot call .sort() on a Vec<f64> — you need .sort_by(|a, b| a.partial_cmp(b).unwrap()).

Booleans and characters

rust
let t = true;
let f: bool = false;

let c = 'z';
let heart = '❤';
let emoji = '🦀';

A char is 4 bytes and holds a Unicode scalar value, not a byte. 'a' as u32 == 97. Note single quotes for char, double quotes for string literals — they are entirely different types.

Type inference and casting

Rust infers types locally but never converts implicitly:

rust
let a: u8 = 10;
let b: u32 = 20;
// let c = a + b;         // ❌ E0308: expected u8, found u32
let c = a as u32 + b;     // ✅ explicit cast
let d = u32::from(a) + b; // ✅ better: lossless conversion, no silent truncation

as is a truncating cast: 300i32 as u8 == 44. Prefer From/TryFrom when correctness matters:

rust
let big: i64 = 300;
let small: Result<u8, _> = u8::try_from(big);   // Err — value doesn't fit

Parsing from strings needs an explicit target type:

rust
let n: i32 = "42".parse().expect("not a number");
let m = "42".parse::<i32>().unwrap();   // turbofish form

2.5 Compound types

Tuples — fixed length, mixed types

rust
let tup: (i32, f64, char) = (500, 6.4, 'x');

let (a, b, c) = tup;         // destructuring
let first = tup.0;           // index access
println!("{a} {b} {c} {first}");

let unit: () = ();           // the "unit" type: zero-size, means "no value"

Functions that return nothing actually return (). Tuples are great for returning two or three related values; beyond that, use a struct (module 06) so the fields have names.

Arrays — fixed length, one type, stack allocated

rust
let a = [1, 2, 3, 4, 5];              // [i32; 5]
let b: [i32; 5] = [1, 2, 3, 4, 5];
let zeros = [0u8; 1024];              // 1024 zeros

println!("{}", a[0]);
println!("{}", a.len());

The length is part of the type: [i32; 3] and [i32; 4] are different types. That's why arrays are rare in application code — you usually want Vec<T> (module 09), which grows.

Out-of-bounds access is checked:

rust
let idx = 10;
// let v = a[idx];   // panics: index out of bounds: the len is 5 but the index is 10
let v = a.get(idx);  // ✅ Option<&i32> -> None

This bounds check is the one runtime cost Rust does pay — and the optimizer removes it whenever it can prove the index is in range (e.g. in a for loop over the array).

2.6 Stack and heap (the minimum you need)

StackHeap
Allocationpush/pop, extremely fastsearch for a free block, slower
Sizemust be known at compile timecan be decided at runtime
Lifetimetied to the enclosing scopeuntil explicitly freed
Examplesi32, bool, char, [u8; 16], &TString, Vec<T>, Box<T>
rust
let n = 5;                       // 4 bytes on the stack
let s = String::from("hello");   // 24 bytes on the stack (ptr, len, cap)
                                 // + 5 bytes on the heap holding "hello"

A String value on the stack is a three-word "fat pointer": a pointer to heap bytes, a length, and a capacity. Understanding this picture is exactly what makes module 04 (ownership) click, so hold on to it.

stack                     heap
┌──────────────┐          ┌───┬───┬───┬───┬───┐
│ ptr ─────────┼─────────►│ h │ e │ l │ l │ o │
│ len  = 5     │          └───┴───┴───┴───┴───┘
│ cap  = 5     │
└──────────────┘

Why the stack/heap split decides so much later

Take the two most common types you will use and put them side by side:

rust
let a = 5;                          // i32 — entirely on the stack
let b = String::from("hello");      // String — a small record on the stack,
                                    //          the text itself in the heap

a is four bytes of number sitting directly on the stack. Copying it means copying four bytes: trivially cheap, and afterwards there are simply two independent numbers.

b is different. On the stack sits a small three-part record — where the text is in the heap, how long it is, and how much room was reserved. The characters themselves are elsewhere. Copying that record would give you two records pointing at the same heap text, and then two owners would each try to clean it up. That is the double-free bug that has haunted C for fifty years.

Rust's answer is module 04 in one line: it copies the small record and then forbids you from using the original. Nothing is duplicated, nothing is freed twice, and it costs nothing at runtime.

You do not need to fully understand that yet. You need to leave this module able to say, for any value: is it entirely on the stack, or does it own something on the heap?

Analogy — the desk and the warehouse

The stack is your desk: small items, exact known sizes, stacked and cleared in strict order, and reaching for anything on it is instant. The heap is the warehouse out back: room for things of any size, but you keep only a tracking slip on your desk and every access is a walk. String is a slip on the desk pointing at a crate in the warehouse — which is exactly why moving one is cheap and copying one is not.

Jargon buster

Every term this module used, in ordinary words. Nothing here is optional vocabulary — these are the words the compiler's error messages will use when talking to you.

TermIn plain English
bindingThe connection between a name and a value, made with let. Rust says binding rather than variable because the thing is not automatically variable.
immutableCannot be changed after it is set. The default in Rust.
mutable (mut)Explicitly allowed to change.
shadowingDeclaring a new binding with a name already in use. The old value still exists, but the name now refers to the new one.
stackFast, strictly ordered memory for values whose size is known in advance.
heapFlexible memory for values whose size is decided while the program runs.
scalar typeA single value: an integer, a floating-point number, a boolean, a character.
compound typeA value made of several values: a tuple or an array.
constant (const)A value fixed at compile time, usable anywhere, written in SCREAMING_CASE.
overflowA number growing past what its type can hold. Rust panics in debug builds rather than silently wrapping.

If you get stuck

The errors this module actually produces, what each one means, and what to do about it. Find yours here before searching anywhere else.

What you seeWhat it meansWhat to do
error[E0384]: cannot assign twice to immutable variableYou assigned to a binding that was never declared changeable.Either add mut at the declaration, or use shadowing (let x = ...) if the old value is not needed.
error[E0308]: mismatched typesYou gave a value of one type where another was required.Read the two type names in the message. The fix is often a conversion: x as f64, or .to_string().
cannot find value ... in this scopeThe binding either does not exist or has gone out of scope.A binding declared inside braces disappears at the closing brace. Declare it outside if it must survive.
attempt to add with overflowA number exceeded its type's range at runtime, in a debug build.Use a bigger type (i64), or the explicit methods checked_add, saturating_add, wrapping_add.

Now make it stick: work through the drills for this module, then carry on to Module 03 — Control Flow & Functions.