← Fundamentals
Fundamentals

Immutable updates and persistent data

How do you “change” a value you never mutate?

Build a new version while preserving every value an earlier version still needs.

Outcome

Write an update that returns a new value, say which parts it shares with the old one, build new values along the path to a nested change, and keep versions that later edits cannot change.

Terminology (5)Terms used in this lesson

Term on the front, definition on the back. Paste with tabs between fields and a new line between cards, or import the download in Anki as Basic.

Immutable update
Producing a new value with a change instead of changing the existing value.
Structural sharing
A new value reusing the unchanged parts of the old one instead of copying them.
Persistent data
Data whose earlier versions stay available and unchanged after an update.
Path copy
Building new values for every level between the outer value and the changed part.
Snapshot
A saved version that nothing will change afterwards.

An update that retains the old version

An immutable update produces a new version while keeping the earlier one usable. Persistent data retains earlier versions across updates; structural sharing can reuse unchanged parts instead of copying everything.

That only works if an update builds a new value instead of changing the old one, including any part the two still share. A fresh outer container does not establish independence of its nested data. Follow the actual field types and copying operations before writing through a retained reference.

01Updating without mutation

An update returns a new value and leaves the old one alone

A trip planner keeps the planned trip and the updated one side by side, and keeps every earlier plan so an edit can be undone.

The planner first proposes a longer trip while retaining the planned duration. Predict both day counts, then inspect what the selected language’s comparison expression actually compares.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Clone, PartialEq)]

struct Trip {
    city: String,
    days: u32,
}

fn with_days(trip: &Trip, days: u32) -> Trip {
    Trip {
        days,
        ..trip.clone()
    }
}

fn main() {
    let trip = Trip {
        city: "Oslo".to_owned(),
        days: 3,
    };
    let later = with_days(&trip, 5);

    println!("{} {} {}", trip.days, later.days, trip == later);
}
What is printed?
Rust · terminal.sh
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
rustc --edition=2024 main.rs && ./main

Use the selected language’s command. Trace both the returned value and every access path the caller retains; a writable local binding does not by itself say which storage is shared.

02What the new value shares

A new outer value may still share the parts inside it

The planner now changes part of an itinerary. Before adding a hotel proposal, this stop-list probe checks what an outer update actually copied. Predict the sharing test and the retained trip’s first stop.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Clone)]

struct Trip {
    days: u32,
    stops: Vec<String>,
}

fn main() {
    let trip = Trip {
        days: 3,
        stops: vec!["Bergen".to_owned(), "Flam".to_owned()],
    };
    let mut later = Trip {
        days: 5,
        ..trip.clone()
    };

    later.stops[0] = "Oslo".to_owned();

    println!(
        "{} {} {}",
        std::ptr::eq(later.stops.as_ptr(), trip.stops.as_ptr()),
        trip.stops[0],
        later.days
    );
}
What is printed?

03Keeping versions

A history keeps versions only if later edits cannot reach them

Undo restores an earlier state only if its saved storage survives later writes. This flat-plan probe saves before and after a duration change. Predict what the saved entries retain.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
#[derive(Clone)]

struct Trip {
    city: String,
    days: u32,
}

fn main() {
    let mut history: Vec<Trip> = Vec::new();
    let mut trip = Trip {
        city: "Oslo".to_owned(),
        days: 3,
    };

    history.push(trip.clone());
    trip.days = 5;
    history.push(trip.clone());

    println!("{} {} {}", history[0].days, history[1].days, trip.city);
}
What is printed?

04Each language’s trap

Read-only, receivers, moves and fluent setters

Each program looks like it keeps the old value intact. Predict what happens.

main.rs
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
struct Trip {
    city: String,
    days: u32,
}

fn main() {
    let trip = Trip {
        city: "Oslo".to_owned(),
        days: 3,
    };
    let later = Trip { days: 5, ..trip };

    println!("{} {}", later.days, trip.city);
}
What does rustc do?

05Repair the trip planner

More days, another night, then undo

The planner needs independent proposals for two more days and an extra hotel night. Its history then needs to restore complete earlier plans after duration edits, including edits made after undoing a previous change.

Each file contains its imports, reader and complete caller.

Repair the trip planner

Compare planned and proposed days, retain the nested hotel plan, then restore complete earlier versions.

  1. easy · F-IMMUT-V4-1 Plan two more days
  2. medium · F-IMMUT-V4-2 Add a hotel night
  3. hard · F-IMMUT-V4-3 Undo plan edits
In the frontend Send a proposed value back to its owner Optional

A client parent passes a flat planned trip and a proposal callback. This button sends a new city/days value; the parent decides whether to store or display it. The child does not assign to the planned prop.

Example.tsx
Follow appearance
GitHub Light
GitHub Dark
Rosé Pine
Catppuccin Mocha
VS Code Dark+
"use client";

type Trip = { city: string; days: number };
type Props = { planned: Trip; onPropose: (next: Trip) => void };

export default function MoreDays({ planned, onPropose }: Props) {
  return (
    <button onClick={() => onPropose({ ...planned, days: planned.days + 1 })}>
      Propose one more day
    </button>
  );
}

The click handler creates a new ordinary object from the current prop’s primitive fields. Calling onPropose hands that value to the client parent.

Sources: React: Passing props,Svelte: Props.

Sources

Report a problem in this lesson

For typos, mistakes and things that don’t work. We read every report and fix what’s wrong, but we don’t reply here, so a question won’t get an answer.