The Programming Shortcut
You know more than you think.
If you have written programs in one language, any language, you already have most of what every other language is made of. You know how to name a value and change it later. You know how to make a decision, repeat something, and wrap a piece of work in a function so you can call it again. You have probably had a function call itself and watched it work, which still feels a little like magic the first few times.
That knowledge is the shortcut. Not a shortcut in the sense of cutting corners or skipping the hard parts, but the oldest shortcut there is: using what you already know to get somewhere new faster.
Most programming tutorials don’t take it. They start every language from zero, as if you had never seen a loop, and spend the first hour on things you could explain to them. Then, right when the language gets interesting, they run out of room.
This series goes the other way. It skips what you know, and spends its time on the part you don’t.
One language, one idea
Each article in The Programming Shortcut is about one programming concept, taught through one language that happens to be especially good at teaching it. Rust is the best place to learn about ownership, because its compiler won’t let you ignore it. Go is a lovely place to learn about programs that do several things at once. PHP makes it obvious what “request and response” means, because a PHP page lives for one request and then forgets everything.
So the articles aren’t language tutorials. There are excellent complete tutorials for every language here, written by the people who make those languages, and each article points you to them at the end. What you get here is the one idea the language does best, taught as a programming idea, with the language as the vehicle. When you finish an article you should understand the concept well enough to spot it in a language you haven’t met yet.
The articles are short on purpose. Each one is meant to be read in a single sitting, with a terminal or a browser open beside it.
And you can start anywhere. No article depends on another one. Read the one whose concept you’re curious about, skip the ones you’re not, come back later, or never. When an article uses an idea that another article teaches, it explains it in a sentence and links there, so you can keep reading without a detour, or take the detour if you like.
What you already know
Every article assumes you know these, from any language:
| Idea | You might know it as |
|---|---|
| Variables | let, var, const, int x =, x = |
| Conditionals | if, else, switch |
| Loops | for, while, repeat |
| Functions | func, fn, def, function, methods |
| Recursion | a function that calls itself |
| Arrays | lists, slices, vectors, [1, 2, 3] |
| Records | structs, objects, data class, a bundle of named fields |
None of these are taught again. If an article needs one, it names it and moves on. That is not a judgment about how hard these ideas were to learn. They were hard, and you learned them, and now they belong to you in every language you will ever use.
If a row on that list is new to you, that’s fine too. Learn it in the language you already have, then come back. The series will still be here.
The shortcut tables
Near the top of each article is a small table that shows what carries over. It looks something like this:
| What you know | lux | Go |
|---|---|---|
| a struct | struct | struct |
| a value that might be missing | Option | the zero value, or nil |
| errors you expect | Result | a value, err pair |
Read it row by row. The left column is the idea. The other columns show how two languages spell it. When a row looks the same in both columns, you can stop thinking about it. When a row looks different, that’s where the article will slow down.
The lux column is there because this series grew out of lux, a small language made for learning to program (more at anderix.com/lux). If you learned lux first, the column is your shortcut. If you learned Python, or Java, or something else entirely, read the left column and fill in your own language from memory. You won’t need lux for anything in this series. It’s one starting point among many.
The question every language answers
Here is a question that sorts programming languages more cleanly than almost any other, and that most people never think to ask: when are types checked?
A type is the kind of value something is: a number, a piece of text, a true or false. Every language has types. What differs is when the language notices that you used the wrong one. Some notice before your program runs at all. Some notice the moment the wrong line actually runs. And some never notice, and do their best with what you gave them.
The easiest way to see the difference is to make the same mistake in several languages and watch what each one does about it.
Here is the mistake. A function that expects text gets a number instead. And the mistake is hidden inside a branch that doesn’t run, because the score is 75 and the branch only runs above 100:
func shout(text: string) -> string {
return text + "!"
}
let score = 75
if score > 100 {
print(shout(42))
}
print(shout("done"))
Run that with lux run and lux refuses. It reads the whole program before running
any of it, including the branch that would never run, and it stops at the mistake:
error: `shout` expects `text` to be string, but got int
--> score.lux:7:17
TypeScript does the same, and its checker, tsc, reports the mistake before
anything runs:
function shout(text: string): string {
return text + "!";
}
const score = 75;
if (score > 100) {
console.log(shout(42));
}
console.log(shout("done"));
score.ts(7,21): error TS2345: Argument of type 'number' is not assignable to parameter of type 'string'.
Now the same program in three more languages. Each of these runs happily and prints
done!:
<?php
declare(strict_types=1);
function shout(string $text): string {
return $text . "!";
}
$score = 75;
if ($score > 100) {
echo shout(42), "\n";
}
echo shout("done"), "\n";
def shout(text: str) -> str:
return text + "!"
score = 75
if score > 100:
print(shout(42))
print(shout("done"))
function shout(text) {
return text + "!";
}
const score = 75;
if (score > 100) {
console.log(shout(42));
}
console.log(shout("done"));
The mistake is still there in all three. Nobody looked at it yet. So change the score to 150, so that the branch runs, and look again.
PHP stops with a TypeError the moment it reaches the line: shout() was promised
a string and got an int. PHP checks the types you declare, but only when the line
actually runs. (That declare(strict_types=1) line matters. Without it, PHP quietly
turns 42 into “42” and carries on.)
Python stops too, but look at what it complains about: unsupported operand type(s) for +: 'int' and 'str'. It never checked the text: str in the function’s first
line. That annotation is a type hint, a note for people and for outside tools, and
the language itself doesn’t enforce it. Python failed only because adding a number to
a piece of text made no sense.
JavaScript doesn’t stop at all. It prints 42! and then done!, because it was
happy to turn the number into text for you. Nothing checked the type, because
plain JavaScript has no way to say what type text should be.
| Language | When types are checked |
|---|---|
| lux | before running, every branch |
| TypeScript | before running, by tsc; then the types are erased and plain JavaScript runs |
| PHP | at runtime, when the line actually runs |
| Python | never by the language; only by outside tools such as mypy |
| JavaScript | never |
Checking before running is called static checking. Checking while running is dynamic checking. Neither is the right answer. A language that checks everything up front catches mistakes in code you haven’t tested yet, and it asks you to say more about your types in return. A language that checks late or never lets you write less and try things faster, and it trusts you to test every branch. Many of the articles in this series live somewhere on that line, and most of them will tell you where.
Hints that answer back
Every article closes with a hint: one small thing to do, not read, that sends you into the language’s own tools. A compiler that explains its error messages. A shell where you can type one line at a time and see what happens. The manual that came with the language and has been on your disk since you installed it.
The idea is that by the end of an article, the language itself becomes your teacher. The hint gives you your first question to bring it.
Each article also has a small project, and every project file ends with a comment block called “Try this next…”: more hints, going further than the article did. If you open the file, you will find more than the article showed you.
The articles
Each article teaches one concept, through the language that teaches it best.
| Article | The concept |
|---|---|
| Rust | Ownership and borrowing, enforced by the compiler |
| Swift | Protocols and generics: describing what a type can do |
| Go | Concurrency by message passing: goroutines and channels |
| Dart | UI as a function of state, plus async |
| Kotlin | Structured concurrency: coroutines, scopes and cancellation |
| C# | Value and reference semantics: what a variable actually holds |
| Java | Null and exceptions: defensive programming without a safety net |
| C | Memory: how data lives in the machine, and the structures built on it |
| C++ | Ownership and resource lifetime, by convention |
| Python | Standing on libraries: using other people’s code, and duck typing |
| JavaScript | Event-driven programming: code that waits for things to happen |
| TypeScript | Static checking as a tool you choose |
| PHP | Request and response: stateless programs on a server |
Three more pieces cover working habits rather than language ideas, so they aren’t tied to any one language:
| Piece | The concept |
|---|---|
| Testing | Writing code that checks your code |
| Debugging | Finding out what a program is actually doing |
| Version control | Saving, comparing and undoing your work |
Where each concept lives
When an article uses a concept it doesn’t teach, it links to the article that does. This is the map those links follow.
| Concept | Taught in | Also appears in |
|---|---|---|
| Ownership and borrowing, enforced | Rust | C++, C |
| Ownership and resource lifetime, by convention | C++ | Rust, C |
| Memory, pointers and data structures | C | C++, Rust |
| Protocols, interfaces and generics | Swift | Go, Kotlin, Java, C# |
| Concurrency by message passing | Go | Kotlin |
| Structured concurrency and cancellation | Kotlin | Go |
| UI as a function of state | Dart | Swift, Kotlin |
| Value and reference semantics | C# | Swift, C |
| Null and exceptions | Java | Kotlin, C#, Dart |
| Standing on libraries, duck typing | Python | JavaScript, PHP |
| Event-driven programming | JavaScript | Dart |
| Static checking as a choice, type erasure | TypeScript | Python, PHP |
| Request and response, stateless servers | PHP | JavaScript |
| Testing | Testing | Rust, Go |
| Debugging | Debugging | C |
| Version control | Version control |
A few smaller ideas turn up in many articles without being the main subject of any. Each has one home where it gets its fullest explanation:
| Concept | Home | Also appears in |
|---|---|---|
Values that might be missing (Option) | Rust | Java, Kotlin, Swift, Dart |
Errors as values (Result) | Rust | Java, Go |
| Enums that carry data (sum types) | Rust | Swift, Kotlin, TypeScript, C# |
| Exhaustive matching | Rust | Swift, TypeScript, C#, Kotlin |
async and await | JavaScript | Dart, C# |
| When types are checked | this introduction | Python, JavaScript, TypeScript, PHP |
If you’d like a path
No order is required, but some articles make good neighbors. If one of these themes interests you, here is a route through it:
| Path | Route |
|---|---|
| Ownership | C, then C++, then Rust: no ownership, then ownership by convention, then ownership the compiler enforces |
| The web | “HTML is easy!”, then JavaScript, TypeScript and PHP |
| Concurrency | Go and Kotlin, in either order |
| Values and types | C#, then Swift |
| Apps | Dart, Kotlin and Swift |
Try it yourself
Take the shout program and write it in the language you know best. Run it with a
score of 75, then with 150. Before each run, guess what will happen.
Whatever your language does, you now know where it sits on the line between checking early and checking never. That’s one question you can ask of every language you meet from here on, and you just answered it for your own.
Tested with lux 0.21.2, TypeScript 7.0.2, Node.js 26.13.1, Python 3.13.5 and PHP 8.4.28, November 2026.
The Programming Shortcut: Rust
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about ownership and borrowing, enforced by the compiler.
Rust is a language that keeps track of who is responsible for every value in your program, so that you don’t have to.
That sounds like a small thing. It isn’t. Every program that builds text, grows a list or reads a file is quietly borrowing memory from the computer, and somebody has to give it back at the right moment. Not too early, not twice, not never. Most languages answer that question for you while the program runs, and charge a little speed for it. A few hand the job to you and wish you luck. Rust answers it before the program runs, by reading your code and checking a handful of rules.
You already follow those rules in your head, most of the time, without names for them. Rust gives them names, writes them down, and checks every one. And when it refuses your program, it tells you which rule you broke, where, and usually what to do about it. Rust grew up among people writing a web browser, where a memory mistake is a crash at best and a security hole at worst. You get the benefit of their strictness for free, with a compiler that behaves like a patient teacher.
You already know half of it
Here is what carries over. Everything on the left you already have in some form.
| What you know | lux | Rust |
|---|---|---|
| a name that holds still | let | let |
| a name that can change | var | let mut |
| a function | func shout(text: string) -> string | fn shout(text: &str) -> String |
| a record | struct | struct |
| a list that grows | [int] | Vec<i64> |
| text | string | String when you own it, &str when you borrow it |
| a value that might be missing | Option<int>: some(x) or none | Option<i64>: Some(x) or None |
| an error you expect | Result<int, string>: ok(x) or err(e) | Result<i64, String>: Ok(x) or Err(e) |
| a value that is one of several shapes | enum | enum |
| covering every case | match | match |
Look at the text row and the function row. That & and the two kinds of text are
where this article lives. Nearly everything else is the same idea with a different
spelling.
If you have lux programs lying around, you have a shortcut nobody else does. Run this on one of them:
lux convert rust yours.lux > main.rs
It prints your program in Rust. Read it with one question in mind: where did all
those .clone() calls come from? By the end of this article you’ll know, and you’ll
know why Rust written by hand mostly doesn’t need them.
Cargo, and a compiler that talks back
You need one tool: cargo, which creates Rust projects, builds them and runs them.
It comes with Rust. On Linux or macOS, one command installs both:
curl --proto '=https' --tlsv1.2 -sSf https://sh.rustup.rs | sh
On Windows, or if you’d like to read before you pipe a script into your shell, the install page has the details.
Now make a project and run it:
cargo new ownership
cd ownership
cargo run
Cargo builds a tiny program it wrote for you and runs it, and you see
Hello, world!. The program lives in src/main.rs. From now on, you edit
src/main.rs, then cargo run. Every Rust example in this article is a whole
program you can paste over that file and run.
The other half of the job is reading what the compiler says when it refuses. Rust’s
error messages are long, and that’s a kindness. Each one has a code like E0382, a
picture of your code with arrows pointing at the lines involved, and often a help:
line with a suggested fix. Read them top to bottom, the way you’d read a note from a
colleague. You’ll be doing a lot of that in a minute.
Somebody has to clean up
Some values are small and fixed: a number, a true or false. Others grow. A piece of text can be one letter or a whole novel, and a list can hold three items or three million. Those values live in memory the program asks for while it runs, and when the program is done with one, that memory should go back.
The hard part is knowing when “done” is. Languages have settled on three answers.
In C, you decide. You ask for memory, and later you hand it back yourself with a call
to free. Forget, and the program slowly fills up. Do it twice, or too soon, and you
get crashes that show up far from the mistake. (The C article shows what that
memory looks like up close.)
In Python, Java, JavaScript, Go and most other languages, a garbage collector decides. That’s a part of the language that runs alongside your program, now and then finds values that nothing can reach anymore, and frees them. It’s safe and comfortable, and it costs some speed and some control over when things happen.
Rust takes a third road. The compiler decides, ahead of time, by following rules
about who owns each value. There’s no garbage collector running, and no free for
you to forget. The cost is that you have to write code the compiler can follow.
Every value has one owner
Here are the rules, as the official Rust book states them:
Each value in Rust has an owner. There can only be one owner at a time. When the owner goes out of scope, the value will be dropped.
The owner is usually a variable. Out of scope means the closing brace of the block where that variable was made. Dropped means cleaned up: the memory goes back.
fn main() {
let greeting = String::from("hello");
println!("{greeting}");
}
String::from makes a piece of text the program owns, and greeting owns it. When
main reaches its closing brace, greeting goes out of scope and the text is
dropped. You didn’t write anything to make that happen. That’s the first rule doing
its work.
Now give the text a second name:
fn main() {
let greeting = String::from("hello");
let other = greeting;
println!("{other}");
println!("{greeting}");
}
Run it, and Rust refuses:
error[E0382]: borrow of moved value: `greeting`
--> src/main.rs:5:16
|
2 | let greeting = String::from("hello");
| -------- move occurs because `greeting` has type `String`, which does not implement the `Copy` trait
3 | let other = greeting;
| -------- value moved here
4 | println!("{other}");
5 | println!("{greeting}");
| ^^^^^^^^ value borrowed here after move
In Python or JavaScript, other = greeting gives one piece of text two names. Rust
can’t allow that, because of the third rule: if both names owned the text, both
would drop it at the end of main, and the same memory would be handed back twice.
So let other = greeting doesn’t share the text. It moves it. other is the owner
now, greeting no longer holds anything you’re allowed to use, and the compiler
won’t let you read it.
Read the error again with that in mind. It names the move (“value moved here”) and the later use, and it points at both.
Numbers don’t behave this way:
fn main() {
let a = 5;
let b = a;
println!("{a} {b}");
}
That runs. Small, fixed-size values like numbers are cheap to copy, so Rust copies
them instead of moving them. That’s what the error meant by the Copy trait: a label
for types that get copied on assignment. Text and lists aren’t on that list, because
copying them could mean copying a novel.
If you learned lux first, you’ve never had to think about this, because lux gives
every name its own copy: assign an array to a new name, change the new one, and the
old one stays as it was. That’s what all those .clone() calls in lux convert’s
output are doing. They make a copy everywhere lux would have, so nothing ever moves.
Handing a value to a function
Calling a function is another way to move a value:
fn shout(text: String) -> String {
text + "!"
}
fn main() {
let name = String::from("Ada");
let loud = shout(name);
println!("{loud}");
println!("{name}");
}
The same error, for the same reason. shout takes a String, so the text moves into
shout’s parameter, and shout drops it (or hands it back as part of the result)
when it finishes. main gave it away.
You have three ways out. You can clone it, with shout(name.clone()), which makes
a second copy for shout to own. You can have shout return the original along with
its result, which gets clumsy fast. Or you can let shout look at the text without
owning it. That last one is the everyday answer, and it has a name.
Borrowing: looking without taking
A reference is a value that points at another value without owning it. You make one
with &, and handing someone a reference is called borrowing.
fn shout(text: &str) -> String {
format!("{text}!")
}
fn main() {
let name = String::from("Ada");
let loud = shout(&name);
println!("{loud}");
println!("{name}");
}
&name lends the text to shout for the length of the call. &str is Rust’s type for
borrowed text: a view of some characters that somebody else owns. shout builds a new
String with format! and returns it, and that new text is owned by loud. Nothing
moved out of name, so both lines print.
Sometimes a function needs to change what it borrows. That takes a mutable reference,
written &mut:
fn add_cheer(text: &mut String) {
text.push_str(", hooray!");
}
fn main() {
let mut name = String::from("Ada");
add_cheer(&mut name);
println!("{name}");
}
mut appears twice, and both are deliberate. let mut says the variable may change.
&mut name at the call says this particular call may change it. You can see, reading
main alone, which calls might touch your data and which can only look.
Borrowing has two rules of its own, and between them they cover most of what the compiler will ever tell you:
At any moment, a value can have many shared borrows (
&) or one mutable borrow (&mut), but not both. A borrow can’t outlive the owner it borrowed from.
Many readers, or one writer. And nobody keeps a reference after the thing it points at is gone. The next two sections show why each one is there.
Many readers, or one writer
Here’s a program that looks harmless:
fn main() {
let mut names = vec![String::from("Ada"), String::from("Grace")];
let first = &names[0];
names.push(String::from("Linus"));
println!("{first}");
}
vec! makes a Vec, Rust’s list that grows. first borrows the first name. Then
push adds a name to the list, which needs a mutable borrow of names, and Rust
refuses:
error[E0502]: cannot borrow `names` as mutable because it is also borrowed as immutable
--> src/main.rs:4:5
|
3 | let first = &names[0];
| ----- immutable borrow occurs here
4 | names.push(String::from("Linus"));
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ mutable borrow occurs here
5 | println!("{first}");
| ----- immutable borrow later used here
Why does it care? A Vec keeps its items side by side in one block of memory. When
the block is full, push asks for a bigger block, moves every item across, and gives
the old block back. If that happened here, first would still point into the old
block, at memory that no longer belongs to the program. That’s called a dangling
reference, and in C or C++ the same program compiles, and usually works, until one day it
prints garbage or crashes.
Rust doesn’t try to predict whether this particular push will need a bigger block.
It applies the rule: while someone is reading, nobody writes. Move the println! above
the push, and the borrow in first is finished before the write starts, so the
program runs.
A borrow can’t outlive its owner
The second rule catches the other way a reference goes bad:
fn main() {
let label;
{
let word = String::from("temporary");
label = &word;
}
println!("{label}");
}
error[E0597]: `word` does not live long enough
--> src/main.rs:5:17
|
4 | let word = String::from("temporary");
| ---- binding `word` declared here
5 | label = &word;
| ^^^^^ borrowed value does not live long enough
6 | }
| - `word` dropped here while still borrowed
7 | println!("{label}");
| ----- borrow later used here
word is dropped at the inner closing brace, and label still points at it. The
error draws the timeline for you: declared here, borrowed here, dropped here, used too
late here.
The stretch of code where a reference is valid is called its lifetime. Rust works
out lifetimes on its own almost everywhere. Now and then it can’t, and asks you to
write one down with a mark like 'a. That’s a topic for later, and you won’t need it
in this article.
Put the pieces together and that’s the bargain. Every value has one owner that drops it. Moving hands it over. Borrowing lends it out, to many readers or one writer, never past the owner’s end. The checker that enforces the borrowing rules is called the borrow checker, and it’s the part of the compiler you’ll argue with most, and learn the most from.
If you came here from C++
You know most of this already, by convention. A Rust
StringorVecowns its memory the way astd::stringorstd::unique_ptrdoes, and drops it at the end of scope: RAII (resource acquisition is initialization), as you’re used to. The differences are in what’s checked. In Rust, moving is the default and copying is the thing you ask for (.clone()), the reverse of C++. Afterstd::move, a C++ object is left in a “valid but unspecified state” and you may keep using it; after a Rust move, using the old name is a compile error. And a C++ reference or iterator can dangle after apush_backor a returned local, where Rust’s borrow checker refuses the program. The C++ article teaches ownership as a discipline you keep; this one is that discipline, enforced.
Values that come in shapes
There’s one more idea Rust leans on everywhere, and you’ll meet it the moment you read
a file or look something up in a list. It also answers a question you may not have
asked yet: if Rust has no null, how does a function say “there’s nothing here”?
A record says a value is this and that: a point is an x and a y. An enum in Rust says a value is this or that: one of a fixed set of cases, and each case can carry its own data. A type like this is often called a sum type.
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Dot,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle(width, height) => width * height,
Shape::Dot => 0.0,
}
}
fn main() {
let shapes = vec![Shape::Circle(1.0), Shape::Rectangle(2.0, 3.0), Shape::Dot];
for shape in &shapes {
println!("{}", area(shape));
}
}
A circle carries a radius, a rectangle carries two sides, a dot carries nothing. (f64
is a number with a fractional part.) match picks the arm for the case in hand and unpacks its data
into names you can use. Notice the ownership here too: area borrows each shape, and
for shape in &shapes walks the list by reference, so main still owns everything at
the end.
Now delete the Dot arm and run it:
enum Shape {
Circle(f64),
Rectangle(f64, f64),
Dot,
}
fn area(shape: &Shape) -> f64 {
match shape {
Shape::Circle(radius) => 3.14159 * radius * radius,
Shape::Rectangle(width, height) => width * height,
}
}
fn main() {
println!("{}", area(&Shape::Dot));
}
error[E0004]: non-exhaustive patterns: `&Shape::Dot` not covered
That’s exhaustive matching: a match must cover every case, or the program doesn’t
compile. Its real value shows up later. Add a Triangle case to Shape six months
from now, and the compiler lists every match in your program that needs a new arm.
Two enums in Rust’s standard library do most of the everyday work. The first is
Option, and here is all of it:
enum Option<T> {
None,
Some(T),
}
T is a placeholder for any type, so Option<i64> is “maybe a number” and
Option<&String> is “maybe a borrowed piece of text”. (Writing one definition that
works for every type is called generics; the Swift article is where this
series teaches them.) Rust has no null. A value that might be missing says so in its
type, and since getting at what’s inside means a match, you can’t forget the empty
case:
fn main() {
let names: Vec<String> = Vec::new();
match names.first() {
Some(name) => println!("first: {name}"),
None => println!("the list is empty"),
}
}
first returns an Option<&String>. Look at what’s inside the Some: a borrow.
first doesn’t hand you the name, it lets you look at it, and the list keeps owning
it. Ownership and enums meet all the time like this.
The second is Result, for things that can fail with a reason:
enum Result<T, E> {
Ok(T),
Err(E),
}
fn main() {
for text in ["42", "forty-two"] {
match text.parse::<i64>() {
Ok(number) => println!("{text} is {number}"),
Err(error) => println!("{text}: {error}"),
}
}
}
parse::<i64>() tries to read a number out of text and returns a Result: Ok with
the number, or Err with what went wrong. Errors are ordinary values that you match on.
Many languages use exceptions instead, where a failure jumps out of the function to
whatever code is waiting to catch it; the Java article covers that style.
Go returns a value and an error side by side, and the Go article shows that.
Rust puts both possibilities in one type and makes you open it.
Where Rust says no to a good program
In most languages, a program that is correct gets to run. Rust doesn’t promise that. The borrow checker only accepts what it can prove safe, and some correct programs are beyond what it can prove. You’ll write one sooner or later, look at it, know it’s fine, and get refused anyway.
The usual trouble spot is data that points at itself in a circle. A list where every
item knows the one before and the one after, a family tree where children know their
parents, a game where every character holds a reference to the others: none of these
has one obvious owner, and one owner is the rule. Rust has tools for these cases.
Rc lets several owners share a value and drops it when the last one lets go.
RefCell moves the borrowing rules from compile time to run time, so breaking them
crashes the program instead of stopping the build. They work. They’re also a step away
from the guarantee you came here for.
Beware of reaching for
.clone()andRc<RefCell<…>>just to quiet the borrow checker. Cloning a short string to get unstuck is fine while you’re learning, andlux convertdoes it everywhere because it has to. But when you find yourself wrapping your data inRc<RefCell<…>>so the errors go away, stop. That’s the compiler telling you the design has no clear owner. Pick one. Let one struct own the data, pass borrows down into functions, return new values back up, and when items need to refer to each other, store their positions in aVecinstead of references. The code gets simpler, and the errors go away for a better reason.
A word counter that borrows its words
Time to put ownership to work on a real file. This small command-line tool reads a text file, finds its ten most common words, prints them, and saves the list next to the file. Make a new project:
cargo new wordfreq
cd wordfreq
Replace src/main.rs with this:
use std::env;
use std::fs;
fn main() {
let path = match env::args().nth(1) {
Some(path) => path,
None => {
eprintln!("usage: cargo run -- <file>");
return;
}
};
let text = match fs::read_to_string(&path) {
Ok(text) => text,
Err(error) => {
eprintln!("can't read {path}: {error}");
return;
}
};
let words = split_words(&text);
let mut counts = tally(words);
sort_by_count(&mut counts);
let report = render(&path, &counts);
print!("{report}");
let out_path = format!("{path}.counts.txt");
match fs::write(&out_path, report) {
Ok(()) => println!("Saved to {out_path}"),
Err(error) => eprintln!("can't write {out_path}: {error}"),
}
}
fn split_words(text: &str) -> Vec<&str> {
let mut words = Vec::new();
for word in text.split(|c: char| !c.is_alphanumeric()) {
if !word.is_empty() {
words.push(word);
}
}
words
}
fn tally(mut words: Vec<&str>) -> Vec<(&str, usize)> {
words.sort();
let mut counts: Vec<(&str, usize)> = Vec::new();
for word in words {
let n = counts.len();
if n > 0 && counts[n - 1].0 == word {
counts[n - 1].1 += 1;
} else {
counts.push((word, 1));
}
}
counts
}
fn sort_by_count(counts: &mut Vec<(&str, usize)>) {
counts.sort_by(|a, b| b.1.cmp(&a.1));
}
fn render(path: &str, counts: &[(&str, usize)]) -> String {
let mut report = format!("The ten most common words in {path}:\n");
for (word, count) in counts.iter().take(10) {
report += &format!("{count:>5} {word}\n");
}
report
}
Then point it at its own source code. Everything after -- goes to your program
instead of to Cargo:
cargo run -- src/main.rs
The ten most common words in src/main.rs:
14 counts
13 path
11 words
10 let
8 1
8 str
8 word
7 Vec
7 mut
6 n
Saved to src/main.rs.counts.txt
Now follow the values, because every one of them has an owner.
main owns path and text. Getting each one meant opening an enum: nth(1) returns
an Option, since you might not have given a file name, and read_to_string returns a
Result, since the file might not be there. Run cargo run with no file, or with a
file that doesn’t exist, and you’ll see the None and Err arms at work.
split_words(&text) borrows the text and returns a Vec<&str>, a list of borrowed
words. No word is copied. Each &str is a view into text, pointing at a few
characters in the middle of it. (The |c: char| ... part is a tiny unnamed function
that tells split where to cut: at anything that isn’t a letter or digit.) Because the
words borrow from text, the borrow checker won’t let text be dropped while they’re
still in use. You didn’t have to say that. With one borrowed input and a borrowed
output, Rust works out that the output borrows from the input.
tally(words) takes the list itself, with no &. The list moves into tally, which
now owns it, so tally is free to sort it in place before counting the runs of equal
words. main can’t use words after this line, and doesn’t need to. What comes back
is a list of pairs, a borrowed word and a count (usize is Rust’s type for counts and
sizes).
sort_by_count(&mut counts) lends the counts out to be changed, and the &mut at the
call tells you so. The little function inside compares two pairs by their counts, the
bigger one first.
render(&path, &counts) only reads, so it borrows both, and it returns a brand new
String that main owns as report.
Finally, fs::write(&out_path, report) takes report with no &. That’s a move.
It’s the last thing that happens to report, so giving it away costs nothing. Try
adding println!("{report}"); after the write and ask the compiler what it thinks.
The full file is in this series’ projects/rust/ folder, with more ideas to try at the
bottom.
What’s left out
Everything left out builds on what you just learned. Writing lifetimes by hand
('a) is the next step for functions whose borrows Rust can’t work out alone. Traits
are Rust’s way of saying what a type can do, and they’re how generics get their power.
Box, Rc and RefCell are the standard tools for ownership shapes beyond “one owner,
many borrowers”. Threads are where ownership pays off most: the same rules that stopped
the dangling reference also stop two threads from writing the same data at once. The
? operator shortens the match on a Result to one character. Iterators and
closures, which the project dipped a toe into, deserve their own chapter. And Cargo has
a test runner built in, cargo test; the Testing piece teaches the
habit with Go’s runner, and it carries straight over.
When you want more, the Rust project’s own material is excellent. The Rust Programming Language, known as the Book, is the standard tutorial, and its fourth chapter covers ownership at greater length. Rust by Example teaches through short runnable programs, and Rustlings gives you small broken exercises to fix while you read.
Ask the compiler why
Every error in this article had a code, and every code has an essay behind it, already on your machine. Run this:
rustc --explain E0382
It explains the use-after-move error from the start of this article, with examples of
how to fix it. Bring it one question: when the compiler’s help: line suggests
.clone(), what does the explanation suggest instead, and which would you pick for
shout?
Related
- C++ teaches ownership and resource lifetime as a convention you keep, and is the step before this one on the ownership path.
- C shows the memory that ownership manages, handed out and handed back by hand.
- Java covers
nulland exceptions, the approachOptionandResultreplace. - Go returns errors as a value and an error side by side.
- Swift teaches generics, the idea behind
Option<T>. - Testing covers the habit of checking your own code, with Go’s built-in runner.
Tested with Rust 1.100 and lux 0.21.2, November 2026.
The Programming Shortcut: Swift
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about protocols and generics: describing what a type can do.
The safe way is the short way
Swift is a language where the careful version of a program is usually the shortest one too.
Apple introduced it in 2014 for the people who write apps for iPhones and Macs. Before Swift, those people wrote Objective-C, a language from the early 1980s that let you do almost anything and caught very little of it. Swift was built to catch those mistakes while you’re still typing, without making you type more to get the help. It’s open source now and runs on Linux and Windows as well, but you can still feel who it was made for: app writers on deadlines, who would rather hear about a bug from the compiler than from a user.
Much of that safety comes from one habit. Most languages ask of a value, what is this? Swift keeps asking a second question: what can this do? Apple’s own team gave a conference talk in 2015 called “Protocol-Oriented Programming in Swift”, and the standard library is built that way from top to bottom.
A protocol is how Swift writes down an answer to “what can this do?” Generics are how a function asks for one. Together they’re the idea in this article, and they travel well. Java, Go, C# and TypeScript call protocols interfaces, and Rust calls them traits. Learn the idea once, here, and you’ll recognize it in every one of them.
In practice, you get to write one function where you would have written five.
What you already have
| What you know | lux | Swift |
|---|---|---|
| a record | struct | struct |
| a value that might be missing | Option<int> | Int? |
| an enum whose cases carry data | enum with payloads | enum with associated values |
| taking an enum apart | match | switch |
| errors you expect | Result | throws, or Result |
A few notes on those rows, and then we can leave them alone.
A Swift struct is a value type: assigning one to a new variable copies it, so
two variables never share the same struct. That idea has its own article,
C#. Int? is Swift’s optional, a value that is either there or
nil, and Swift makes you check which before you use it; the fullest short
explanation of that idea lives in Rust. A Swift switch over an enum
must cover every case or it won’t compile, which is called
exhaustive matching.
If you know lux, you have a shortcut nobody else has. Write a small struct that
compares two points, and save it as point.lux:
struct Point {
x: int
y: int
}
let here = Point(x: 3, y: 4)
print(here == Point(x: 3, y: 4))
Now run lux convert swift point.lux and read what comes back:
struct Point: Equatable {
var x: Int
var y: Int
}
let here = Point(x: 3, y: 4)
print(here == Point(x: 3, y: 4))
Look at the first line. That : Equatable is a protocol, and lux had to add it.
In lux, any two structs of the same type can be compared with ==. In Swift,
only a type that promises it can be compared gets ==, and Equatable is
that promise. You’ve been relying on a protocol all along without ever writing
one down. This article is about writing them down.
Edit, then swift run
If you have Xcode on a Mac, you already have Swift. Otherwise, swift.org/install has an installer for macOS, Linux and Windows. Check that it worked:
swift --version
Everything happens through that one swift command. Make a folder for a
package, a folder Swift knows how to build and run:
mkdir Shapes
cd Shapes
swift package init --type executable
mv Sources/Shapes/Shapes.swift Sources/Shapes/main.swift
The init line writes a starter program. The mv line renames it, because a
file called main.swift is special: it runs from top to bottom, like a lux file
or a script, with no main function needed. Open Sources/Shapes/main.swift,
replace everything in it with this one line, and save:
print("Hello, shapes")
Then, from the Shapes folder:
swift run
The first run takes a few seconds while Swift builds things; after that it’s
quick. You’ll see a few lines about building, then Hello, shapes.
Every example below works the same way: edit main.swift, run swift run,
read what comes back. When Swift refuses, the error message is usually the most
useful thing on the screen, so read it before you change anything.
What it is, and what it can do
Every typed function makes a promise about its parameters. Write
func area(of c: Circle) and you’ve said what you’ll accept: a circle,
and nothing else. That’s precise. It’s also narrow. The day you want the same
function for squares, you have two familiar choices: write it again with
Square in it, or make one big enum with a case for every shape.
There’s a third choice. Instead of saying what the value is, say what it must be able to do. “Give me anything that can tell me its area.” That sentence is a protocol.
A protocol is a promise
Here’s that sentence in Swift, and two types that keep it:
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double {
return 3.14159 * radius * radius
}
}
struct Square: Shape {
var side: Double
func area() -> Double {
return side * side
}
}
print(Circle(radius: 2).area())
print(Square(side: 3).area())
Put it in main.swift and swift run it. You’ll get 12.56636 and 9.0.
(Double is Swift’s floating-point number.)
Three things are going on. The protocol block lists requirements: what a
type must provide, with no code for how. It’s a job description, not a worker.
Each struct then says : Shape, which means “I promise to keep the Shape
protocol.” Swift calls this conforming. And each one keeps the promise by
writing an area method, which is a function written inside a type, where it
can read that type’s fields directly. A circle knows its radius; a square knows
its side. Each computes its area its own way, and the protocol doesn’t care how.
The compiler holds you to it
A promise is only useful if somebody checks it. Make a promise you don’t keep:
protocol Shape {
func area() -> Double
}
struct Triangle: Shape {
var base: Double
var height: Double
}
Swift won’t build it:
error: type 'Triangle' does not conform to protocol 'Shape'
note: protocol requires function 'area()' with type '() -> Double'
Notice who caught it, and when. Not a test, not a user, but the compiler, before anything ran. The note even tells you which requirement is missing.
The check works the other way too. A type that happens to have an area()
method, but never says : Shape, doesn’t count as a Shape. Swift wants the
promise said out loud. That’s a real difference from duck typing, where a
language only asks “does this have an area method?” at the moment you call
it; Python is the home of that idea. Go sits in between: its
interfaces are checked by the compiler, but a type satisfies one without saying
so.
One function for a whole family
If you’ve written lux, you’ve met the problem this solves. A lux function that joins two arrays of strings can’t join two arrays of numbers. You write it twice, and the only difference is the type. lux let you make your own types; Swift lets you say what a whole family of types has in common, and write one function for all of them.
Here is that join, written once:
func joined<T>(_ first: [T], _ second: [T]) -> [T] {
var out: [T] = []
for item in first {
out.append(item)
}
for item in second {
out.append(item)
}
return out
}
print(joined([1, 2], [3]))
print(joined(["ace"], ["king", "queen"]))
The new part is <T>. It’s a type parameter: a placeholder that stands where
a type would go, filled in fresh at every call. In the first call T is Int.
In the second it’s String. You don’t say so; Swift works it out from the
arguments. A function written with a type parameter is called generic, because
it’s written once for any type. (The _ before each parameter just means
callers don’t have to write its name.)
That’s the easy half. What can joined actually do with a T? Store it,
copy it, hand it back. That’s all, because T could be anything,
and Swift only lets you do what’s true of everything. Try finding the biggest
item in an array:
func largest<T>(_ items: [T]) -> T? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item > best {
best = item
}
}
return best
}
print(largest([3, 9, 4]) as Any)
Swift refuses: binary operator '>' cannot be applied to two 'T' operands.
It’s right. Not every type can be compared with >, and a T might be a type
with no idea what “bigger” means.
So narrow it down. Ask for any type at all, as long as it keeps one particular promise:
func largest<T: Comparable>(_ items: [T]) -> T? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item > best {
best = item
}
}
return best
}
if let biggest = largest([3, 9, 4]) {
print(biggest)
}
if let last = largest(["pear", "apple", "zucchini"]) {
print(last)
}
T: Comparable is a constraint. It reads “T can be any type that conforms
to Comparable,” and Comparable is a protocol from Swift’s standard library.
Its only requirement you have to write is <; <=, > and >= come with
default versions. Inside the function you may use only what the
constraint promises, and outside, Swift will only let callers pass types that
keep it. (if let unwraps an optional: the block runs only if a value is there,
with the name bound to it.)
This is where the two halves meet. A protocol describes an ability. A constraint asks for one. Generic code is code that says “I don’t care what you are, only what you can do,” and the compiler checks both sides of that deal.
Generics keep the type; any makes a box
Your own protocols work as constraints the same way. Back to shapes:
func larger<S: Shape>(_ a: S, _ b: S) -> S {
if a.area() >= b.area() {
return a
}
return b
}
let big = larger(Circle(radius: 1), Circle(radius: 3))
print(big.radius)
That prints 3.0. Look at what came back: a Circle, not a vague “some shape,”
so big.radius works. A generic function remembers which type it was handed.
The flip side is that S is one type per call. Ask
larger(Circle(radius: 1), Square(side: 2)) and Swift says conflicting arguments to generic parameter 'S' ('Circle' vs. 'Square'). Both arguments
must be the same kind of shape.
Sometimes you want a mix, though. A drawing has circles and squares. For that,
Swift has any:
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
var total = 0.0
for shape in shapes {
total += shape.area()
}
print(total)
Think of any Shape as a box. It can hold a value of any type that conforms,
it remembers what’s inside, and it passes calls through to it. The price is that
you can only use what the protocol promises: shapes[0].radius won’t compile,
because a box labeled “Shape” doesn’t know it’s holding a circle.
So there’s a choice to make each time. Use a generic when you work on one type at
a time and want it back intact. Use any when you truly need a mix. Most
languages with interfaces make the same split under different names; Rust, for
example, writes them impl Trait and dyn Trait.
Your type, the library’s code
Comparable isn’t magic reserved for numbers and strings. It’s
an ordinary protocol, and your types can keep it too:
struct Planet: Comparable {
var name: String
var moons: Int
static func < (a: Planet, b: Planet) -> Bool {
return a.moons < b.moons
}
}
let planets = [
Planet(name: "Earth", moons: 1),
Planet(name: "Mars", moons: 2),
Planet(name: "Venus", moons: 0),
]
for planet in planets.sorted() {
print(planet.name)
}
if let most = planets.max() {
print("Most moons:", most.name)
}
That prints Venus, Earth, Mars, and then Most moons: Mars. You wrote one
function: what < means for planets. (It’s static because it belongs to the
type rather than to any one planet, which is how Swift writes operators.) In
return, sorted() and max() started working on your type, and so would the
largest function from earlier. Somebody wrote those generic functions long ago
against the Comparable promise. They never heard of planets, and they didn’t
need to.
Comparable also needs ==, through Equatable, but Swift writes that one for
you when every field can already be compared. That’s what lux leaned on back in
the converted Point.
Protocols can hand out free behavior as well. An extension adds code to an existing type or protocol, and an extension on a protocol gives every conforming type the new method at once:
extension Shape {
func describe() -> String {
return "a shape with area \(area())"
}
}
print(Square(side: 3).describe())
Circle and Square never wrote describe, and both have it. (The \( )
inside a string drops a value into the text.) The standard library does this
constantly, as the hint at the end will show you.
A closed list or an open family
You may be thinking that an enum could do some of this. In lux you’d write
enum Shape with a circle case and a square case, and take it apart with
match. That’s a sum type, a value that is exactly one of a fixed list of
cases (Rust is its home), and it’s a fine design. It’s just a
different promise.
An enum is a closed list. Every case is known in one place, so the compiler can
check that each switch covers them all. Adding a new function over shapes is
easy. Adding a new shape means visiting every switch you’ve written.
A protocol is an open family. Anyone can add a new conforming type later, in another file, without touching a line of existing code. Adding a new shape is easy. Adding a new requirement means visiting every type.
Neither one wins. Ask which you expect to grow: the kinds of things, or the things you do with them.
Against the grain
Swift’s checks are strong, and nearly every one has a one-character exit. It’s
!.
You’ve seen that a box of any Shape hides what’s inside. You can ask to open
it. shape as? Circle is the careful way: it gives you an optional, a circle if
it was one and nil if not. shape as! Circle is the other way. It says “trust
me,” and if you’re wrong, the program stops:
protocol Shape {
func area() -> Double
}
struct Circle: Shape {
var radius: Double
func area() -> Double { return 3.14159 * radius * radius }
}
struct Square: Shape {
var side: Double
func area() -> Double { return side * side }
}
let shapes: [any Shape] = [Circle(radius: 1), Square(side: 2)]
let second = shapes[1] as! Circle
print(second.radius)
Could not cast value of type 'Shapes.Square' (0x…) to 'Shapes.Circle' (0x…).
The same ! on an optional, like largest([Int]())!, crashes on an empty array.
The compiler checked everything it could and then took your word for the rest.
Each ! is a spot where you’ve told Swift to stop checking. Reach for as? and
if let first.
Beware of SwiftUI before protocols make sense. SwiftUI is Apple’s way of building app screens, and it’s the first thing many people try. Its starter code looks like this:
struct ContentView: View {
var body: some View {
Text("Hello")
}
}
Every part of that is this article. View is a protocol. body is its
requirement. some View means “one particular type that conforms to View,
which I’m not going to name,” the mirror image of a generic parameter: there
the caller picks the type, here the function does. Start with SwiftUI and these
lines are an incantation you copy. Start with protocols, in a plain package like
the one you just made, and they read as ordinary code. Spend a week in plain
packages first. SwiftUI will still be there, and it will make sense.
A small project: packing a bag
The project is a bag you’re packing for a trip. Three very different types all keep one promise: each can tell you its name and its weight in grams. Then two generic functions work on any of them, and one function works on a mixed bag.
Make the package and rename its file, as before:
mkdir Pack
cd Pack
swift package init --type executable
mv Sources/Pack/Pack.swift Sources/Pack/main.swift
Replace everything in Sources/Pack/main.swift with this:
protocol Packable {
var name: String { get }
var grams: Int { get }
}
extension Packable {
func label() -> String {
return "\(name), \(grams) g"
}
}
struct Book: Packable {
var title: String
var pages: Int
var name: String { title }
var grams: Int { pages * 2 }
}
struct Bottle: Packable {
var milliliters: Int
var name: String { "water bottle" }
var grams: Int { 150 + milliliters }
}
enum Snack: Packable {
case apple
case trailMix(bags: Int)
case sandwich
var name: String {
switch self {
case .apple: return "apple"
case .trailMix(let bags): return "trail mix x\(bags)"
case .sandwich: return "sandwich"
}
}
var grams: Int {
switch self {
case .apple: return 180
case .trailMix(let bags): return 120 * bags
case .sandwich: return 250
}
}
}
func heaviest<Item: Packable>(_ items: [Item]) -> Item? {
if items.isEmpty {
return nil
}
var best = items[0]
for item in items {
if item.grams > best.grams {
best = item
}
}
return best
}
func fitting<Item: Packable>(_ items: [Item], under limit: Int) -> [Item] {
var packed: [Item] = []
var total = 0
for item in items {
if total + item.grams <= limit {
packed.append(item)
total += item.grams
}
}
return packed
}
func totalGrams(_ items: [any Packable]) -> Int {
var total = 0
for item in items {
total += item.grams
}
return total
}
let books = [
Book(title: "The Hobbit", pages: 310),
Book(title: "Dune", pages: 688),
Book(title: "A Wizard of Earthsea", pages: 183),
]
let snacks: [Snack] = [.apple, .trailMix(bags: 3), .sandwich]
if let book = heaviest(books) {
print("Heaviest book: \(book.label()), \(book.pages) pages")
}
if let snack = heaviest(snacks) {
print("Heaviest snack: \(snack.label())")
}
print("Books that fit in 1000 g:")
for book in fitting(books, under: 1000) {
print(" \(book.label())")
}
let bag: [any Packable] = [books[0], Bottle(milliliters: 750), Snack.apple, Snack.sandwich]
print("In the bag:")
for item in bag {
print(" \(item.label())")
}
print("Total: \(totalGrams(bag)) g")
Run swift run, and after the build lines you’ll see:
Heaviest book: Dune, 1376 g, 688 pages
Heaviest snack: trail mix x3, 360 g
Books that fit in 1000 g:
The Hobbit, 620 g
A Wizard of Earthsea, 366 g
In the bag:
The Hobbit, 620 g
water bottle, 900 g
apple, 180 g
sandwich, 250 g
Total: 1950 g
A few things to look for as you read it.
The protocol asks for properties this time, not methods. var grams: Int { get }
means “you must have a grams I can read,” and it doesn’t say how. Book
answers with a computed property, var grams: Int { pages * 2 }, which is a
field whose value is worked out each time it’s read. Bottle computes its own
way. Snack isn’t even a struct: it’s an enum, and it keeps the promise with a
switch. The protocol asked what, and each type chose how.
heaviest is one function, and it worked on books and on snacks. When you
handed it books, it handed back a Book, so book.pages compiles on the next
line. label() came free from the extension; none of the three types
wrote it.
The bag is a mix, so it’s [any Packable], and totalGrams takes the boxed
kind. Try heaviest(bag) and Swift says type 'any Packable' cannot conform to 'Packable'. That sounds strange until you remember the box: a generic function
needs one real type to fill in for Item, and a box of mixed things isn’t one.
The file in the series repository ends with more things to try.
What’s left out, and where to go next
This article left a lot of Swift out. Protocols can have their own
type placeholders, called associated types; that’s how a collection says what
kind of element it holds. Generic code can ask for several promises at once, or
add conditions with where. A type can be made to conform to a protocol after
the fact, in an extension. And Swift has classes, inheritance, its own approach
to concurrency, and a great deal more that isn’t about protocols at all.
When you want more, go to the people who make the language. The Swift Programming Language is the official book, free online, and its chapters on Protocols and Generics pick up where this article stops. swift.org/documentation has the rest.
Ask Swift what it promised
You made Planet comparable by writing one function, <. So where did >
come from? Ask Swift. In a terminal, start its interactive shell:
swift repl
Then type this, and press Return:
:type lookup Comparable
You’ll see the protocol itself: its requirements, the protocol it builds on, and
the extensions that hand out free behavior. Find < in the list, then find the
operators you never wrote. Then try :type lookup on Equatable, or on a type
you use every day, and ask of each one: what can this do, and who promised it?
Type :quit when you’re done.
Related
- C#: value and reference semantics, the reason a Swift struct is copied when you assign it.
- Rust: optionals, enums that carry data, and exhaustive matching, the closed-list side of the choice in this article.
- Python: duck typing, the opposite answer to “does this value keep the promise?”
Tested with Swift 6.2.4 and lux 0.21.2, November 2026.
The Programming Shortcut: Go
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about concurrency by message passing.
Boring on purpose
Go is a language made for big teams who want to write plain programs.
It was started at Google in 2007 by Robert Griesemer, Rob Pike and Ken Thompson, and went public in 2009. They wanted a language that compiled fast, ran fast, and stayed readable in a code base far too big for any one person to hold in their head. So they built one with very few features, one way to format your code, and almost nothing to be clever with.
People sometimes call Go boring. Its fans agree, and mean it as praise. Boring code is code the next person can read.
A boring language gets out of your way. You’ll recognize most Go the moment you see it. And that leaves room for the one part of Go that is not boring at all: it was built from the first day to do several things at once. Go made that part of the language itself, with a keyword and a type, and gave it a motto. By the end of this article you’ll know what the motto means and why it works.
You can already read Go
Here is what carries over. Read it row by row; where the columns look alike, you can stop thinking.
| What you know | lux | Go |
|---|---|---|
| where the program starts | func main() | func main() |
| a record | struct Job { id: int } | type Job struct { id int } |
| a new variable | let x = 3, var x = 3 | x := 3 |
| a loop over an array | for job in jobs | for _, job := range jobs |
| printing | print(a, b) | fmt.Println(a, b) |
| a value that might be missing | Option | the zero value, or nil |
| an error you expect | Result | a value, err pair |
| several things at once | (none) | goroutines and channels |
The last row is the new one, and it’s the rest of this article. Two rows above it
differ more than they look: Go has no Option or Result type. A missing value is a variable’s
zero value (0, "", or nil, meaning “points at nothing”), and a function that
can fail hands back two things, the answer and an error, which you check with an
ordinary if. That’s the idea of errors as plain values, explained more fully in
the Rust article.
If you learned lux, there’s an even shorter shortcut. lux convert go turns your
lux program into Go source, so you can read something you wrote, in Go, before you
write a line of Go yourself.
Edit, run, repeat
The one tool for this article is the go command. Install Go from
go.dev/doc/install, then check it with
go version.
Make a folder, and tell Go it holds a program:
mkdir squares
cd squares
go mod init squares
go mod init writes a small file called go.mod, which names your program (Go
calls it a module) and records the Go version. You won’t need to touch it.
Now the program. If you know lux, here is one you could have written:
struct Job {
id: int
size: int
}
func work(job: Job) -> int {
return job.size * job.size
}
func main() {
let jobs = [Job(id: 1, size: 3), Job(id: 2, size: 5), Job(id: 3, size: 7)]
var total = 0
for job in jobs {
let answer = work(job)
print("job", job.id, "->", answer)
total += answer
}
print("total:", total)
}
Save it as squares.lux and run lux convert go squares.lux > main.go. If you
don’t know lux, save this as main.go instead. It’s what the converter writes:
package main
import "fmt"
type Job struct {
id int
size int
}
func work(job Job) int {
return job.size * job.size
}
func main() {
jobs := []Job{Job{id: 1, size: 3}, Job{id: 2, size: 5}, Job{id: 3, size: 7}}
total := 0
for _, job := range jobs {
answer := work(job)
fmt.Println("job", job.id, "->", answer)
total += answer
}
fmt.Println("total:", total)
}
Two small things are new. range hands you two values on each pass, the position
and the element, and the underscore _ says “I don’t need the position.” And
fmt is the package that prints; import "fmt" brings it in.
Then run it:
go run .
job 1 -> 9
job 2 -> 25
job 3 -> 49
total: 83
The dot means “the program in this folder.” You’ll do that a lot: change
main.go, run go run ., read what comes back. Every example
below is a whole program, so you can paste any of them over main.go and run it.
Several things at once
Your squares program does one thing at a time. It works on job 1, then job 2, then job 3. Nothing starts until the thing before it is finished.
That’s fine when each job takes a millionth of a second. It’s less fine when each job is a web request that takes half a second, mostly spent waiting for a server somewhere to answer. A program that does one thing at a time spends most of its life waiting.
Think of a cook making soup and bread. A cook who does one thing at a time puts the soup on and stands watching the pot for an hour, then starts the bread. A real cook puts the soup on, starts the bread while it simmers, and checks on both.
That second cook is doing concurrent work. Concurrency means a program is built from several pieces of work that can be in progress at the same time, each one moving forward whenever it can. It’s related to parallelism, which means work happening at literally the same instant on different processor cores. A concurrent program can run in parallel if your machine has the cores to spare, but the idea is about how you organize the work, not how many cores you have. Rob Pike, one of Go’s designers, gave a good talk on the difference.
Concurrency has a reputation for being hard, and for once the reputation is fair. The hard part is almost never starting several pieces of work. The hard part is letting them talk to each other without stepping on each other’s toes. Go’s answer to that is the idea this article is about: message passing. Pieces of work don’t share things. They send each other messages.
If you learned lux, every program you wrote there had one line of work going on at a time, top to bottom. lux left goroutines out on purpose, because they belong to Go alone. Go keeps that one line of work, and lets you start more of them.
go starts something new
In Go, one of those independent pieces of work is called a goroutine. It is a
function call that runs on its own, alongside everything else. You start one by
putting the word go in front of a call:
package main
import "fmt"
func greet(name string) {
fmt.Println("hello,", name)
}
func main() {
go greet("goroutine")
fmt.Println("main is done")
}
Run it. You’ll almost certainly see only this:
main is done
Where did the greeting go? go greet(...) started the greeting and returned
immediately, without waiting for it. main printed its line and returned, and when
main returns, the program ends. Every other goroutine stops right where it is,
mid-sentence if need be.
Goroutines are cheap. The Go FAQ says a new one starts with a few kilobytes of memory, and that “it is practical to create hundreds of thousands of goroutines” in one program. So starting them is the easy part, as promised. What we’re missing is a way to wait for one, and a way to get an answer back from it. In Go, those turn out to be the same thing.
A channel is a handoff
A channel is a pipe that one goroutine puts values into and another takes values
out of. It has a type, like everything in Go: a chan string carries strings, a
chan int carries ints. You make one with make:
done := make(chan string)
Two operations use the arrow <-, which points the way the value moves. done <- "soup" sends a value into the channel. <-done receives a value out of it.
A channel made this way, an unbuffered channel, holds nothing at all. A send waits until some other goroutine is ready to receive, and a receive waits until someone sends. The two goroutines meet, the value passes from one hand to the other, and both carry on. So a channel does two jobs at once: it delivers a value, and it tells both sides that the other one got there. Effective Go, the language’s own style guide, puts it this way: unbuffered channels “combine communication—the exchange of a value—with synchronization.”
Here is the cook, with two dishes:
package main
import (
"fmt"
"time"
)
func cook(dish string, done chan string) {
time.Sleep(100 * time.Millisecond)
done <- dish + " is ready"
}
func main() {
start := time.Now()
done := make(chan string)
go cook("soup", done)
go cook("bread", done)
fmt.Println(<-done)
fmt.Println(<-done)
fmt.Println("took", time.Since(start).Round(time.Millisecond))
}
time.Sleep pauses a goroutine, standing in for slow work. Each dish takes a tenth
of a second, and there are two of them, so cooking them one after the other would
take two tenths. Run it a few times:
bread is ready
soup is ready
took 100ms
Both dishes cooked at once, so the meal took one tenth of a second. And sometimes soup comes first, sometimes bread. That’s not a bug. The two goroutines are racing to the channel, and whichever gets there first is received first. In a concurrent program, results arrive in the order they finish, not the order you started them.
Notice also that main waited, this time. Each <-done held main still until a
dish arrived, so it couldn’t run off and end the program early. Receiving was the
waiting.
Your program, three jobs at a time
Now go back to the squares program and give each job its own goroutine. Instead of
returning its answer, work sends it down a channel:
package main
import "fmt"
type Job struct {
id int
size int
}
func work(job Job, results chan int) {
results <- job.size * job.size
}
func main() {
jobs := []Job{Job{id: 1, size: 3}, Job{id: 2, size: 5}, Job{id: 3, size: 7}}
results := make(chan int)
for _, job := range jobs {
go work(job, results)
}
total := 0
for range jobs {
answer := <-results
fmt.Println("got", answer)
total += answer
}
fmt.Println("total:", total)
}
The first loop starts three goroutines and moves on without waiting. The second
loop runs once per job (for range jobs repeats that many times without naming
anything) and receives one answer each time. The answers may arrive in any order,
and the total is always 83, because addition doesn’t care about order.
Don’t share, send
Look at who touches total in that program. Only main does. The three workers
never see it. They compute a number and send it, and main adds it up.
That’s on purpose, and it’s the motto. Effective Go says:
Do not communicate by sharing memory; instead, share memory by communicating.
The first half describes the way most concurrent programs were written for decades. Several pieces of work all reach into the same variable, and they each have to be careful not to change it at the same moment as somebody else. Being careful is easy to get wrong, and the mistakes are invisible most of the time.
The second half is Go’s suggestion. Give each piece of data one owner. If anyone else wants it changed, or wants to know its value, they send the owner a message. When only one goroutine ever touches a variable, there is nothing to be careful about.
Once you see this shape, you’ll spot it in other languages too. Erlang and Elixir
build everything from small processes that each own their data and send messages
to each other’s mailboxes. Rust’s standard library has channels with a sender end
and a receiver end. A web page can hand work to a background worker and get the
answer back with postMessage. The spelling changes. The idea is the same: work
that doesn’t share variables, joined by sends and receives.
Closing time
Sometimes the receiver doesn’t know how many values are coming. For that, the
sender can close the channel, which means “there’s nothing more.” A for loop
with range over a channel receives values until the channel is closed, then
stops:
package main
import "fmt"
func countTo(n int, out chan int) {
for i := 1; i <= n; i++ {
out <- i
}
close(out)
}
func main() {
numbers := make(chan int)
go countTo(3, numbers)
for n := range numbers {
fmt.Println(n)
}
fmt.Println("no more numbers")
}
Closing is the sender’s job, never the receiver’s. Sending on a closed channel crashes the program, so only the side that knows when the work is finished should close.
Waiting forever
Because sends and receives wait for each other, it’s possible to wait for someone who will never come. Here’s the smallest way to do it:
package main
import "fmt"
func main() {
ch := make(chan string)
ch <- "hello"
fmt.Println(<-ch)
}
main sends, and waits for a receiver. The only receiver is the next line of
main, which can’t run until the send is done. Nothing can ever move. That’s a
deadlock, and Go notices:
fatal error: all goroutines are asleep - deadlock!
Go can only notice when every goroutine is stuck. If one goroutine is waiting forever while others keep running, nothing complains. That stuck goroutine just sits there, using a little memory, for the rest of the program’s life. It’s called a goroutine leak, and it’s a common quiet bug in concurrent Go.
There’s another way out of this particular deadlock. Give the channel a buffer,
room to hold some values with nobody receiving yet, by passing a size to make:
package main
import "fmt"
func main() {
ch := make(chan string, 1)
ch <- "hello"
fmt.Println(<-ch)
}
Now the channel is a mailbox with room for one letter. The send drops the value in and moves on, and the receive picks it up later. A send only waits once the buffer is full.
Waiting for whichever comes first
One last tool. A select statement waits on several channels at once and takes
whichever one is ready first. It looks like a switch, with a send or receive in
each case. A common use is giving up on slow work:
package main
import (
"fmt"
"time"
)
func cook(dish string, wait time.Duration, done chan string) {
time.Sleep(wait)
done <- dish + " is ready"
}
func main() {
done := make(chan string, 1)
go cook("stew", 500*time.Millisecond, done)
select {
case msg := <-done:
fmt.Println(msg)
case <-time.After(200 * time.Millisecond):
fmt.Println("gave up waiting for the stew")
}
}
time.After hands back a channel that receives a single value once the time is up.
Whichever channel delivers first wins. If both are ready at the same moment, Go
picks one at random, so your program can’t quietly depend on the order you wrote
the cases in. (The done channel has a buffer of one so the stew’s goroutine can
still drop off its message after nobody is listening, instead of waiting forever.)
That’s the core of message passing in Go: start work with go, connect it with
channels, close a channel when you’re done sending, and select when you need to
wait for more than one thing.
The compiler won’t stop you
Go gives you channels. It doesn’t make you use them.
Nothing in Go stops two goroutines from reaching into the same variable. Here are four goroutines, each adding to one shared counter a hundred thousand times:
package main
import "fmt"
var count int
func addMany(done chan bool) {
for range 100_000 {
count++
}
done <- true
}
func main() {
done := make(chan bool)
for range 4 {
go addMany(done)
}
for range 4 {
<-done
}
fmt.Println("count:", count)
}
(for range 4 repeats four times, and var count int declares a variable
outside any function, so every function can see it.)
It compiles without a word of complaint. The answer should be 400,000. On three runs on my machine it printed 199,130, then 400,000, then 226,630.
The reason is that count++ isn’t one step. It reads count, adds one, and writes
the result back. Two goroutines can both read 41, both add one, and both write 42,
and one of the additions is gone. This is a data race: two goroutines touching the
same memory at the same time, at least one of them writing, with nothing deciding
who goes first. Its symptoms come and go from run to run, which makes it miserable
to track down.
Some languages refuse to compile this. Rust’s compiler, for one, won’t let two pieces of concurrent work change the same value unless you prove it’s safe; its rules about who owns what are the subject of the Rust article. Go made a different trade. It trusts you, keeps the language small, and gives you a detector instead. Add one flag to the same command you already use:
go run -race .
==================
WARNING: DATA RACE
Read at 0x000000607098 by goroutine 11:
main.addMany()
main.go:9 +0x39
...
Found 2 data race(s)
exit status 66
The race detector watches the program while it runs and tells you the line where two goroutines collided. It only sees races that happen during that run, so it can’t promise your program is clean, but it catches a great deal. On most systems it needs a C compiler installed, and its documentation says which.
Beware of using channels for everything. Once channels click, it’s tempting to route every bit of shared state through one, with a goroutine standing guard over a counter. For a counter, that’s a lot of machinery. The plain answer is a mutex (short for “mutual exclusion”), a lock that only one goroutine can hold at a time:
package main
import (
"fmt"
"sync"
)
var (
count int
mu sync.Mutex
)
func addMany(done chan bool) {
for range 100_000 {
mu.Lock()
count++
mu.Unlock()
}
done <- true
}
func main() {
done := make(chan bool)
for range 4 {
go addMany(done)
}
for range 4 {
<-done
}
fmt.Println("count:", count)
}
That prints 400,000 every time. My rule: use a channel when work or results move from one goroutine to another, and use a mutex when several goroutines need to read and update one small thing that stays put. If you find yourself writing a goroutine whose only job is to guard a single number, reach for the lock.
A bakery with three bakers
The project is a worker pool, one of the most common shapes in concurrent
programs. A fixed number of workers take jobs from one channel and put results on
another. It’s a bakery: orders come in at the front counter, three bakers bake
them, and main collects the loaves.
Make a new folder and set it up the same way as before:
mkdir bakery
cd bakery
go mod init bakery
Save this as main.go:
package main
import (
"fmt"
"time"
)
const bakers = 3
type Order struct {
id int
bread string
bake time.Duration
}
type Loaf struct {
order Order
baker int
}
func frontCounter(list []Order, orders chan Order) {
for _, order := range list {
orders <- order
}
close(orders)
}
func baker(id int, orders chan Order, loaves chan Loaf) {
for order := range orders {
time.Sleep(order.bake)
loaves <- Loaf{order: order, baker: id}
}
}
func main() {
ms := time.Millisecond
list := []Order{
{1, "sourdough", 400 * ms},
{2, "baguette", 200 * ms},
{3, "rye", 300 * ms},
{4, "brioche", 100 * ms},
{5, "focaccia", 200 * ms},
{6, "pretzel", 100 * ms},
{7, "challah", 300 * ms},
{8, "bagel", 100 * ms},
{9, "ciabatta", 200 * ms},
}
orders := make(chan Order)
loaves := make(chan Loaf)
start := time.Now()
go frontCounter(list, orders)
for id := 1; id <= bakers; id++ {
go baker(id, orders, loaves)
}
made := make([]int, bakers+1)
var alone time.Duration
for range list {
loaf := <-loaves
made[loaf.baker]++
alone += loaf.order.bake
at := time.Since(start).Round(10 * ms)
fmt.Printf("%6v baker %d: order %d, %s\n", at, loaf.baker, loaf.order.id, loaf.order.bread)
}
fmt.Println()
for id := 1; id <= bakers; id++ {
fmt.Printf("baker %d made %d loaves\n", id, made[id])
}
fmt.Println("together:", time.Since(start).Round(10*ms))
fmt.Println("one baker alone:", alone)
}
A time.Duration is a length of time, so 400 * ms is four tenths of a second.
make([]int, bakers+1) makes an array of zeros that can grow (Go calls it a
slice), and fmt.Printf prints with a format, the way printf does in many
languages.
Run it with go run ., and you’ll see something like this:
200ms baker 1: order 2, baguette
300ms baker 1: order 4, brioche
300ms baker 2: order 3, rye
400ms baker 2: order 6, pretzel
400ms baker 3: order 1, sourdough
500ms baker 1: order 5, focaccia
500ms baker 3: order 8, bagel
700ms baker 2: order 7, challah
700ms baker 1: order 9, ciabatta
baker 1 made 4 loaves
baker 2 made 3 loaves
baker 3 made 2 loaves
together: 700ms
one baker alone: 1.9s
Your bakers will split the work a little differently from mine. Nobody assigned order 4 to baker 1. Baker 1 finished the baguette first, so
baker 1 was the one waiting at the orders channel when the brioche came through.
The fast bakers take more orders. Three bakers finished almost two seconds
of baking in seven tenths of one.
Now look at what’s shared. The bakers share nothing but two channels. The tally in
made belongs to main alone, so no lock is needed and no race is possible. The
front counter closes orders when the list runs out, and that’s how every baker’s
for ... range orders loop knows to stop.
Why does the front counter get a goroutine of its own, instead of main sending
the orders itself? Try it and see. The answer is the deadlock from earlier, in a
slightly bigger kitchen.
The project file is in this series’ repository as
projects/go/main.go, and the copy there ends with more
things to try.
What I left out
You haven’t seen sync.WaitGroup, which waits for a group
of goroutines to finish without counting replies, or the context package, which
tells a whole tree of goroutines to stop. Stopping work cleanly is its own big
idea, and it’s the subject of the Kotlin article. I also skipped
channel types that can only send or only receive, the patterns built from chains
of channels, and nearly everything about Go that isn’t concurrency: interfaces,
packages, error handling, testing.
When you want more, Go’s own material is excellent. The concurrency section of A Tour of Go lets you run every example in your browser. Effective Go explains the style behind the motto, and the Go blog’s pipelines article builds bigger shapes out of the pieces you have now.
Look inside a channel
The go command came with a manual, and the source code of Go itself. Ask it how
time.After works:
go doc -src time.After
The function is three lines long, and it hands back a channel. Then run go env GOROOT to find
where Go lives on your disk, and open src/runtime/chan.go inside it. Search for
type hchan struct. That’s what a channel is made of. Bring one question: why is
there a lock in there?
Related
- Kotlin for structured concurrency, where every task you start is also sure to finish.
- Rust for errors as values and for ownership, which stops data races before the program runs.
Tested with Go 1.27.4 and lux 0.21.2, November 2026.
The Programming Shortcut: Dart
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about UI as a function of state.
A language for drawing screens
Dart is a general-purpose language. You can write a command-line tool in it, or a server. But almost nobody comes to Dart for that. People come to Dart because of Flutter, Google’s toolkit for building apps that run on phones, desktops and the web from one codebase. Dart is the language Flutter is written in and the language you write Flutter apps in, and it has grown up around that job.
So here is the reframing: Dart is a language for drawing screens.
That sounds narrow, but drawing screens is where most programmers first meet a problem their first language never posed: the screen has to keep matching the program, while the program keeps changing, and while some of the things it’s waiting for haven’t arrived yet. Flutter’s answer to that problem is one of the most useful ideas in modern programming, and it fits in one line:
The screen is a function of the state.
State is the data your program is holding right now: how many items are in the cart, whether you’re logged in, what the server sent back. The claim is that you never change the screen directly. You change the state, and the screen gets drawn again from it, the way a function’s result gets computed again from its arguments.
This article is about that idea, plus the one thing it needs to survive in the real
world: async, Dart’s way of waiting for slow things without making the screen
wait with you. By the end you should be able to spot the same idea in React, SwiftUI,
Jetpack Compose and whatever comes next.
What you already have
Dart will look familiar. It has curly braces and semicolons, and its classes and functions read like those of Java, C#, Kotlin or TypeScript. Variables, loops, conditionals, functions and lists all work the way you expect, so this article skips them. A few rows differ enough to read side by side:
| What you know | lux | Dart |
|---|---|---|
| a struct | struct | a class with final fields |
| a value that might be missing | Option<int> | int?, and the checker makes you deal with the null |
| an enum whose cases carry data | enum with payloads | a sealed class, one subclass per case |
a match that must cover every case | match | a switch expression, checked for every case |
| showing something | print("hi") | print('hi') for the console, Text('hi') for the screen |
Dart checks types before your program runs, every branch, the way lux and
TypeScript do. (The introduction’s typo demo
shows what that means.) The last row, Text for the screen, is where this article slows down.
Save, press r
You need one tool: Flutter, which brings Dart with it. Follow the install guide for your system, then run this to check that everything is in place:
flutter doctor
Now make an app and start it:
flutter create hello_screen
cd hello_screen
flutter run
flutter create writes a small starter app. flutter run builds it and opens it
as a desktop app on your computer (or asks which device to use, if it finds more
than one). The app is a counter: a number in the middle and a button that adds one
to it.
Press the button a few times, so the counter says 5 or so. Now open
lib/main.dart in any editor, find the text 'You have pushed the button this many times:', and change it to something of your own. Save the file. Go back to the
terminal where flutter run is still running, and press r.
The text changes in under a second. And the counter still says 5.
That’s hot reload: Flutter swaps your new code into the running app without
starting it over. You’ll use it for the rest of this article, and it’s already showing
you the main idea. Your code changed, the screen was drawn again, and the state
(the 5) survived, because the state and the drawing are two separate things. Hot
reload swaps in new code and keeps the old state. Press R (capital) for a
hot restart, which throws the state away too, and the counter goes back to 0.
If you work in VS Code with the Flutter extension, you can make it hot reload every time you save, so the only key you press is save.
The screen is a function of the state
Two ways to keep a screen up to date
Picture a shopping cart screen. It shows a label (“Cart: 3”) and a checkout button that only works when the cart has something in it. When the user adds an item, both have to change.
The older way, still common in many toolkits for graphical user interfaces, is imperative: you keep a handle to each thing on the screen, and when something happens you go and change each one by hand. Set the label’s text. Enable the button. Here it is with plain variables standing in for the label and the button:
var items = 0;
var cartLabel = 'Cart is empty';
var checkoutEnabled = false;
void addItem() {
items++;
cartLabel = 'Cart: $items';
}
void main() {
addItem();
print(cartLabel);
print('Checkout enabled: $checkoutEnabled');
}
Cart: 1
Checkout enabled: false
Did you spot the bug before you ran it? addItem forgot the button. The label says
there’s an item, the button says there isn’t, and the screen is now lying to the
user. Every new thing on the screen is one more line every event handler has to
remember, and the handlers multiply: add item, remove item, empty the cart, load a
saved cart. Somewhere, one of them forgets.
The other way is declarative: you describe what the screen should look like for a given state, and that’s all you write. One function, state in, screen out:
String view(int items) {
final label = items == 0 ? 'Cart is empty' : 'Cart: $items';
final checkout = items > 0 ? 'enabled' : 'disabled';
return '$label | Checkout $checkout';
}
void main() {
var items = 0;
print(view(items));
items++;
print(view(items));
}
Cart is empty | Checkout disabled
Cart: 1 | Checkout enabled
Now the label and the button can’t disagree, because they’re both computed from
the same number every time. There’s nothing to forget. items is the source of
truth: the one place the fact lives. Everything on the screen is derived from it.
If you’ve used lux, you already have half of this. A lux program prints its state. A Flutter screen is its state, printed again every time the state changes.
Who calls the function?
If the screen is a function of the state, somebody has to call that function again
whenever the state changes. In Flutter, you change the state inside a call to
setState, and setState means: “I’ve changed something; draw me again.” Here is
that idea with the framework boiled down to a dozen lines of plain Dart:
class CartScreen {
int items = 0;
void setState(void Function() change) {
change();
print(build());
}
String build() => items == 0 ? 'Cart is empty' : 'Cart: $items';
}
void main() {
final screen = CartScreen();
print(screen.build());
screen.setState(() => screen.items++);
screen.setState(() => screen.items++);
screen.setState(() => screen.items = 0);
}
Cart is empty
Cart: 1
Cart: 2
Cart is empty
setState takes a function, runs it to make the change, then calls build to
redraw. Real Flutter does the same, with two differences. It doesn’t redraw on the
spot: it marks the screen as needing a redraw and does it in time for the next
frame. And build doesn’t return a string. It returns widgets.
Widgets are descriptions
A widget in Flutter is a small, cheap object that describes a piece of the screen: some text, a button, a column holding other widgets. It isn’t the thing on the screen. It’s a description of what should be there, like a sketch handed to a painter. Widgets can’t be changed once they’re made; when the state changes, you make new ones.
A widget that has no state of its own is a StatelessWidget, and it’s a function
of whatever it was given:
class Greeting extends StatelessWidget {
const Greeting({super.key, required this.name});
final String name;
@override
Widget build(BuildContext context) => Text('Hello, $name!');
}
A widget that holds state comes in two parts: the widget itself, and a State
object that keeps the data and builds the description. Here is a cut-down counter in
the same shape as the one you ran a moment ago:
class _CounterState extends State<Counter> {
int _count = 0;
@override
Widget build(BuildContext context) {
return Column(
children: [
Text('Pushed $_count times'),
FilledButton(
onPressed: () => setState(() => _count++),
child: const Text('Push'),
),
],
);
}
}
(The underscore at the start of a name makes it private to the file. That’s a Dart rule, not a Flutter one.)
Read build the way you read view earlier. Given _count, here’s the screen.
Nowhere does the code say “find the text and change it.” When the button is
pressed, the count changes inside setState, Flutter calls build again, and it
gets back a brand-new description.
Then Flutter compares the new description with the previous one and changes only what differs on the real screen. That comparison is why making a whole new description every time isn’t wasteful: you describe everything, and Flutter does the minimum. You get to write code as if you redrew the world from scratch, and the computer gets to do as little as possible.
Give the state a shape
Once the screen is a function of the state, the most useful thing you can do is
make the state say which situations are possible. A screen that loads a
list from the internet is in one of three situations: still loading, loaded, or
failed. You could track that with a few loose variables (isLoading, names,
error) and hope they never contradict each other. Or you could say outright that
the state is exactly one of three cases.
Dart says that with a sealed class: a family of classes where every member is
known in advance. A switch over one must handle every case, and Dart checks that
before the program runs. (This idea of an enum whose cases carry data, and a match
that must cover them all, has its fullest explanation in the
Rust article.)
sealed class Load {}
final class Loading extends Load {}
final class Loaded extends Load {
Loaded(this.names);
final List<String> names;
}
final class Failed extends Load {
Failed(this.why);
final String why;
}
String view(Load state) => switch (state) {
Loading() => 'Spinner goes round…',
Loaded(:final names) => 'Friends: ${names.join(', ')}',
Failed(:final why) => 'Something went wrong: $why',
};
void main() {
print(view(Loading()));
print(view(Loaded(['Ada', 'Grace'])));
print(view(Failed('no network')));
}
Spinner goes round…
Friends: Ada, Grace
Something went wrong: no network
Loaded(:final names) matches a Loaded and pulls its names field out into a
variable of the same name. Now try deleting the Failed line from the switch:
sealed class Load {}
final class Loading extends Load {}
final class Failed extends Load {}
String view(Load state) => switch (state) {
Loading() => 'Spinner goes round…',
};
void main() {
print(view(Loading()));
}
Dart refuses to run it. The type Load is not exhaustively matched by the switch
cases, it says, since it doesn’t match Failed(). That’s a screen state you never
drew, caught before anyone saw a blank page. When your state has a shape, the
checker can tell you whether your screen covers it.
One rule that falls out of all this
If build is a function of the state, it should behave like one. Flutter calls it
whenever it likes: when the state changes, when the window is resized, when a
parent redraws, as often as every frame during an animation. So build
should be quick, and it should only describe. Don’t start a download in build,
or change the state there, or print a receipt. Do those things in response to
events, then change the state, then let build describe the result.
Waiting without freezing
Real state doesn’t arrive all at once. The friends list comes from a server, and the server takes a second. What does the program do during that second?
It mustn’t stop. A Flutter app runs your Dart code on one thread, the same thread that draws the frames. If your code sits and waits for the network, nothing gets drawn: no spinner, no button presses, a window that looks frozen. So Dart doesn’t wait by sitting still. It has an event loop: a queue of small jobs (draw a frame, handle a tap, finish a network request) that the one thread works through one at a time.
Waiting fits into that loop with two pieces. A Future is a value that will exist
later: a ticket you hold while the work goes on elsewhere. await says “pause this
function here until the ticket is ready, and let the loop run other jobs in the
meantime.” A function that uses await is marked async, and it returns a
Future itself. That’s a one-line summary of async and await, which work this
way in many languages; the JavaScript article is where the series
explains them properly.
Watch the loop keep going while one function waits:
import 'dart:async';
Future<String> fetchFriends() async {
await Future.delayed(const Duration(seconds: 1));
return 'Ada, Grace';
}
Future<void> main() async {
final frames = Timer.periodic(
const Duration(milliseconds: 300),
(_) => print(' (frame drawn)'),
);
print('Asking the server…');
final friends = await fetchFriends();
print('Got: $friends');
frames.cancel();
}
Asking the server…
(frame drawn)
(frame drawn)
(frame drawn)
Got: Ada, Grace
The Timer stands in for Flutter drawing frames. While main is paused at
await, the timer’s jobs keep running. Now swap the friendly wait for a stubborn
one, a loop that just spins until the second is up:
import 'dart:async';
Future<String> fetchFriends() async {
final stop = DateTime.now().add(const Duration(seconds: 1));
while (DateTime.now().isBefore(stop)) {}
return 'Ada, Grace';
}
Future<void> main() async {
final frames = Timer.periodic(
const Duration(milliseconds: 300),
(_) => print(' (frame drawn)'),
);
print('Asking the server…');
final friends = await fetchFriends();
print('Got: $friends');
frames.cancel();
}
Asking the server…
Got: Ada, Grace
Not one frame. The function still says async, but it never let go of
the thread, so for a whole second the app would have been a picture of an app.
async doesn’t make work happen somewhere else. It only gives the loop a chance
to run other jobs at each await.
Async, meet state
Here’s where the two ideas lock together. The screen never waits. The screen only ever shows the current state. So waiting becomes a state of its own:
Future<void> _loadFriends() async {
setState(() => _state = Loading());
try {
final names = await fetchFriends();
setState(() => _state = Loaded(names));
} catch (e) {
setState(() => _state = Failed('$e'));
}
}
Set the state to “loading,” and the screen draws a spinner. Await the answer while
the loop keeps drawing frames. When it arrives, set the state to “loaded” or
“failed,” and the screen draws that. A failed request isn’t a crash or a pop-up
thrown from somewhere deep in the code. It’s just another case of the state, and
build already knows how to draw it, because the switch made sure.
That pattern (event, change the state, await, change the state again) is most of what an app does all day.
What Dart doesn’t check for you
Dart’s checker is strict. It won’t let a null slip into an int, and it won’t
let a switch skip a case. So it’s surprising to find that the central promise of
this article is one nobody checks.
Nothing makes you call setState. If you change _count directly, Dart compiles
it, Flutter runs it, and the screen just doesn’t change, because nobody told
Flutter to call build again. No error, no warning. The screen is a function of
the state only as long as you keep telling it when the state changed. It’s a
convention, and you keep it.
await has a catch of its own. While your function is paused, the user can leave
the screen. When the answer arrives a second later, the widget it was meant for is
gone, and calling setState on it is an error Flutter reports at runtime:
setState() called after dispose(). The fix is one line after every await that’s
followed by a setState: if (!mounted) return;, which asks “am I still on
screen?” before touching anything. The _loadFriends fragment above is missing
it. The project below has it, and one of its tests fails without it.
Beware of state-management debates before you have state. Search for Flutter
help and you’ll soon find people arguing about Provider, Riverpod, Bloc, Redux and
a dozen more. These are packages for sharing state across many screens, and each
has fans who will tell you it’s the only sane choice. Ignore them for now. They’re
all answers to “where should state live when lots of widgets need it?”, and you
can’t judge an answer to a question you haven’t had yet. setState and a well
shaped state class will carry you a long way. When passing the same data down
through five layers of widgets starts to hurt, that’s the time to read
Flutter’s own page on the options,
and you’ll know what you’re shopping for.
The slow oracle
The project is in projects/dart/. It’s one screen with an
oracle on it. You ask a question by pressing a button, the oracle thinks for two
seconds, and then it answers. Every fifth time, it gets confused instead.
The oracle’s mood is the state, and it has a shape:
sealed class Mood {}
final class Asleep extends Mood {}
final class Thinking extends Mood {}
final class Spoke extends Mood {
Spoke(this.answer);
final String answer;
}
final class Confused extends Mood {
Confused(this.reason);
final String reason;
}
Alongside it the screen keeps one number, _asked, the count of questions so far.
Everything you see is computed from those two values in build. The headline is a
switch over the mood. The spinner appears only while the oracle is Thinking.
The button is switched off while it thinks (in Flutter, a button whose onPressed
is null is disabled), and its label says “Ask” or “Ask again” depending on
_asked. Not one line of the program turns the spinner off, or re-enables the
button, or changes the label. When the mood changes, those things follow.
Asking is the async pattern from above, with the mounted check in place:
Future<void> _ask() async {
setState(() {
_mood = Thinking();
_asked++;
});
Mood next;
try {
next = Spoke(await consult(_asked));
} catch (e) {
next = Confused('$e');
}
if (!mounted) return;
setState(() => _mood = next);
}
The project comes with widget tests: small programs that build the screen in memory, tap its button, and check what it shows, with no window at all. (Testing in general has its own article.) Run them from the project folder:
cd projects/dart
flutter test
00:00 +0: the screen follows the oracle through a question
00:00 +1: a failed consultation becomes a state too
00:00 +2: leaving while the oracle thinks is safe
00:00 +3: All tests passed!
The tests finish in well under a second, even though the oracle thinks for two.
Widget tests run on a pretend clock, and tester.pump(const Duration(seconds: 2))
moves it forward and redraws, so the test can check the screen at each moment of
the wait: thinking, then answered. Open test/widget_test.dart and you’ll see the
screen-as-function idea from the other side. Each test sets up a state, and then
checks only what’s drawn.
To see the oracle in a window, let Flutter add the platform files the project leaves out, then run it:
flutter create .
flutter run
flutter create . fills in what’s missing and leaves the existing code and tests
alone. Ask a few questions. Then change the words Questions asked: in build, save,
and press r. The new words appear, and the count stays put.
The end of lib/main.dart has more to try, including what happens when you
delete the mounted check, or forget a setState.
What this article skips
This article didn’t cover layout (rows, columns, padding
and how Flutter decides sizes), styling and themes, moving between screens,
animation, talking to the network for real, or reaching the phone’s camera and
sensors. It skipped Stream, Dart’s type for a value that keeps arriving, like
messages in a chat. It skipped isolates, Dart’s way of doing heavy work on
another thread, which is the real answer to the spinning loop above. And it skipped
nearly all of Dart itself.
When you want more, the people who make Dart and Flutter have written it well. The
Dart language tour covers the language, and
Asynchronous programming covers Future and
await in depth. For Flutter, start with the
learning pathway, and read
Start thinking declaratively,
Flutter’s own short page on the idea this article is about.
Read the starter app
Go back to the hello_screen app you made at the start, open lib/main.dart, and
read the comments. Flutter’s starter app is full of notes and “TRY THIS” prompts,
written by the people who made the framework. One of them explains, in a few lines,
what would go wrong if you changed the counter without calling setState.
Bring a question with you: in that file, which lines are the state, and which are the function?
Related
- JavaScript, for
asyncandawaitand code that waits for events. - Rust, for enums that carry data and matches that cover every case.
- Testing, for code that checks your code.
Tested with Dart 3.14 and Flutter 3.50.1, November 2026.
The Programming Shortcut: Kotlin
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about structured concurrency.
Java, with the sharp edges filed off
Kotlin is what happens when the people who build tools for Java programmers spend years watching Java programmers trip over the same things, and then write the language they wish those programmers had.
That’s not far from the real story. Kotlin comes from JetBrains, the company behind the IntelliJ IDEA editor. The project started in 2010 and reached 1.0 in February 2016. It runs on the same Java Virtual Machine (the JVM, the program that runs Java code on every major operating system), it can call any Java library, and Java can call it back. Android supports it as a first-class language, which is where many people first meet it.
So Kotlin isn’t trying to be exotic. It takes a platform that already runs nearly everywhere and removes the parts that cost Java programmers the most time: the missing values nobody checked, the pages of boilerplate, the ceremony around simple things.
Kotlin’s coroutine library came along after many languages had already spent years trying to do several things at once, and it settled on an answer called structured concurrency, one of the clearest ideas in modern programming. Once you’ve seen it, you’ll notice when a language has it, and you’ll miss it when one doesn’t.
What you already have
Most of Kotlin will look familiar. Here’s what carries over:
| What you know | lux | Kotlin |
|---|---|---|
| a name you can’t reassign | let | val |
| a name you can | var | var |
| a function | func add(a: int, b: int) -> int | fun add(a: Int, b: Int): Int |
| a record | struct | data class |
| a value that might be missing | Option<int> | Int? |
| errors you expect | Result | exceptions, with try, catch and finally |
| matching on a value | match | when |
| a function that can pause | (none) | suspend fun |
The first seven rows are things you already know, under a new spelling or as a near
relative, so we won’t stop on them. If Int? is new to you, it means “an Int, or nothing at all”, and
the Rust article gives that idea its full treatment.
Kotlin handles errors with exceptions: an error that jumps out of the function
where it happened and up through every caller until a catch stops it. A finally
block runs on the way out, whether things went well or not. The Java
article is where exceptions get their full story.
The last row is the one that’s new. It’s where we’re headed.
One file, one command
You’ll use one tool: the kotlin command, running a script. A script is a single
file of Kotlin that runs from top to bottom, with no main function and no project
around it. Scripts whose names end in .main.kts get one extra power: a line at the
top can pull in a library, and Kotlin downloads it for you the first time.
If you use SDKMAN, one command installs Kotlin:
sdk install kotlin
Kotlin runs on the JVM, so you’ll need a JDK (Java Development Kit) too. The command-line page covers that and the other ways to install.
Now make a file called breakfast.main.kts and put this in it:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
launch {
delay(1000)
println("tea is ready")
}
launch {
delay(500)
println("toast is ready")
}
println("breakfast started")
}
println("breakfast served")
Run it:
kotlin breakfast.main.kts
The first run takes a few seconds while Kotlin fetches the library named on the first line, kotlinx.coroutines, the official coroutine library from the Kotlin team. After that it comes from a cache on your disk. You should see:
breakfast started
toast is ready
tea is ready
breakfast served
Edit the file, run kotlin on it, read what it printed: that’s all the tooling
this article needs. Every coroutine example below is a complete script you can paste into a file and run
the same way.
Look at the order. “breakfast started” came first, even though it’s the last line in the block. The tea and the toast were both waiting at the same time, and the toast won because its wait was shorter. And “breakfast served” didn’t print until both were done. That last part is the idea this article is about.
A function that can wait
Before the big idea, the small one it rests on.
A coroutine is a piece of work that can pause partway through and pick up again later, without holding anything up while it’s paused. A thread, the operating system’s own unit of “something running”, is the heavier relative you may have met: each one needs its own reserved memory for its function calls and its own place in the operating system’s schedule. Coroutines are much lighter. Many of them can share one thread, taking turns: while one is paused, another runs.
In Kotlin, a function that’s allowed to pause is marked suspend. That’s the new
row in the table. Suspending is Kotlin’s word for pausing in this polite way, and
a suspension point is a place where it can happen, such as a call to delay.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun brew(): String {
delay(1000)
return "tea"
}
suspend fun toast(): String {
delay(500)
return "toast"
}
runBlocking {
val ms = measureTimeMillis {
println(brew())
println(toast())
}
println("one after the other: about $ms ms")
}
That takes about 1,500 milliseconds, because the calls run in order, just like any
function calls you’ve written. suspend doesn’t make anything happen at the same
time. It only says that this function is allowed to pause, so that other work can
run while it waits.
A suspend function can only be called from another suspend function or from
inside a coroutine. runBlocking is the doorway between the two worlds: ordinary
code on the outside, coroutines on the inside. It holds the program at that point
until everything started inside it has finished.
To make things happen at once, you start new coroutines. launch starts one and
moves straight on to the next line without waiting. That’s what the breakfast
script did twice.
Starting things is easy; stopping them is the hard part
Every language that runs several things at once has some way to say “start this,
and don’t wait for it”. In Go it’s go f(), which starts a goroutine and returns at
once (the Go article teaches goroutines and the channels that connect
them). In many languages it’s creating a thread. In JavaScript it’s calling an
async function and not waiting for its answer.
Starting is the easy half. The hard half is three questions. When the function that started a task returns, is the task finished? If the task fails, who hears about it? And if you change your mind, how do you stop it?
With a plain “start and forget”, the answers are: maybe not, maybe nobody, and
good luck. The task has come loose from the code that started it. Kotlin still has
a way to start work like that, called GlobalScope, so you can see it happen:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
@OptIn(DelicateCoroutinesApi::class)
fun startUpload() {
GlobalScope.launch {
delay(100)
println("upload finished")
}
}
runBlocking {
startUpload()
println("main is done")
}
This prints main is done, and that’s all. The upload never finishes, and nothing
tells you. startUpload returned right away, runBlocking had nothing of its own
left to wait for, and the program ended with the upload still in progress. The
library labels GlobalScope a delicate API for this reason, and that @OptIn
line is you signing for it.
If lux was your first language, you already know the promise this idea keeps. A lux program does one thing at a time, top to bottom, and when its last line runs, everything is over. Structured concurrency keeps that promise while letting several things happen at once.
The programmer Nathaniel J. Smith compared a bare “start this” to goto, the old
jump-anywhere instruction, in an essay called Notes on structured
concurrency.
Languages got rid of goto by giving every block a clear beginning and end: you
enter an if or a loop at the top and leave at the bottom. Structured concurrency
does the same for tasks.
Every task has a parent
Here is the rule Kotlin builds everything on:
A coroutine is started inside a scope, and a scope doesn’t end until every coroutine started inside it has ended.
A scope is a block of code that owns the tasks started in it. runBlocking makes
one. So does coroutineScope, which you can use inside any suspend function:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun makeBreakfast() {
coroutineScope {
launch {
delay(1000)
println(" tea is ready")
}
launch {
delay(500)
println(" toast is ready")
}
println(" both started")
}
}
runBlocking {
println("making breakfast")
makeBreakfast()
println("breakfast served")
}
making breakfast
both started
toast is ready
tea is ready
breakfast served
From the outside, makeBreakfast looks like any other function call. You call it,
it does its work, it returns. Inside, two tasks ran at the same time. And the
moment it returns, you know both are done, because the scope wouldn’t let it
return any sooner.
That answers the first question. When the function returns, its tasks are finished.
Each launch inside a scope makes a child of that scope, and children can start
children of their own. So the tasks in a program form a family tree, and the tree
has the same shape as your code: a task lives inside the block that started it,
the way a variable lives inside the block that declared it. You can see every
task’s lifetime by looking at the indentation.
Compare that with GlobalScope. A task launched there has no parent. It’s an
orphan, and nobody waits for orphans.
Getting answers back
launch is for work that doesn’t hand anything back. When you want a result, use
async, which starts a coroutine and gives you a handle to its answer. Calling
await() on the handle suspends until the answer is ready.
Some readers know async and await from another language, where they mean “a
function that can pause” and “pause here until the answer arrives”; the
JavaScript article is their home. In Kotlin the pausing part is
suspend, and async is something narrower: a way to start a task that has an
answer.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
import kotlin.system.measureTimeMillis
suspend fun brew(): String {
delay(1000)
return "tea"
}
suspend fun toast(): String {
delay(500)
return "toast"
}
runBlocking {
val ms = measureTimeMillis {
val drink = async { brew() }
val food = async { toast() }
println("${drink.await()} and ${food.await()}")
}
println("at the same time: about $ms ms")
}
These are the same two functions as before, unchanged. This time it takes about
1,000 milliseconds instead of 1,500, because both waits overlap. Notice that
nothing about brew or toast had to change. Whether work runs in sequence or at
once is decided by the caller, not by the function.
An async task is a child too, so the same rule holds. If you start one and never
call await, its scope still waits for it to finish.
When one task fails
Now the second question: if a task fails, who hears about it?
In a scope, a failure goes up to the parent, and the parent does two things. It cancels all of the failed task’s brothers and sisters, because the job they were part of can’t succeed anymore. Then, once they’ve stopped, it throws the original exception out of the scope, so the code that called it sees the error, like any other function that failed.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun makeBreakfast() {
coroutineScope {
launch {
try {
delay(1000)
println("tea is ready")
} finally {
println("tea: stopped, kettle off")
}
}
launch {
delay(300)
throw IllegalStateException("toast caught fire")
}
}
}
runBlocking {
try {
makeBreakfast()
} catch (e: IllegalStateException) {
println("no breakfast: ${e.message}")
}
}
tea: stopped, kettle off
no breakfast: toast caught fire
The tea never finished. When the toast failed, the scope cancelled the tea, the
tea’s finally block ran, and only then did the exception come out of
makeBreakfast, where an ordinary try and catch caught it.
That’s the second answer. A failure goes to the parent, and from there to the caller, the same path an exception takes through ordinary function calls. Nothing fails silently in a background corner.
Sometimes you want the opposite, where one child’s failure leaves the others alone.
Kotlin has supervisorScope for that. It’s a deliberate choice you make, not the
default.
Stopping on purpose
The third question: if you change your mind, how do you stop it?
Cancelling a coroutine means asking it to stop early. launch returns a Job,
a handle on the task, and job.cancel() asks the task to stop:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val job = launch {
try {
repeat(10) {
println("chunk $it")
delay(100)
}
} finally {
println("cleaning up")
}
}
delay(350)
job.cancel()
println("cancelled")
}
chunk 0
chunk 1
chunk 2
chunk 3
cancelled
cleaning up
Cancelling a task cancels its children too, and theirs, all the way down the tree. You don’t have to keep a list of everything a task started. Cancel the parent and the family stops.
Kotlin cancels a task by throwing a special exception inside it, called
CancellationException, at its next suspension point. That’s why the finally
block ran: as far as the task could tell, an exception was passing through. It’s
also why finally is the place for cleanup in coroutine code, such as closing a
file or deleting a half-written one.
The most common reason to cancel is time. withTimeoutOrNull runs a block and
cancels it if it takes too long:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
suspend fun slowAnswer(): Int {
delay(2000)
return 42
}
runBlocking {
val quick = withTimeoutOrNull(500) { slowAnswer() }
println("with half a second: $quick")
val patient = withTimeoutOrNull(3000) { slowAnswer() }
println("with three seconds: $patient")
}
with half a second: null
with three seconds: 42
A timeout is just a scope with a clock attached. When time runs out, everything
inside it is cancelled, children included, and null comes back instead of an
answer. Its sibling withTimeout throws an exception instead of returning null.
Cancellation is a request
Here’s where Kotlin asks for your help. In many places, “stop” means stop. In Kotlin, cancellation is cooperative: a coroutine stops only at a suspension point, or when it checks for itself. Code that never pauses never notices it was asked.
Thread.sleep waits without suspending. It’s the old Java way to pause, and it
holds the thread the whole time. Watch what happens under a timeout:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val result = withTimeoutOrNull(300) {
repeat(5) {
Thread.sleep(100)
println("step $it")
}
"finished"
}
println(result)
}
You asked for 300 milliseconds. You got five steps, 500 milliseconds, and
finished, as if the timeout weren’t there. The request to stop arrived, but the
code never paused long enough to hear it.
The same thing happens to any long calculation, a loop that crunches numbers with
no delay in it. The fix is to check. ensureActive() throws the cancellation
exception if the coroutine has been asked to stop, and does nothing otherwise:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val result = withTimeoutOrNull(300) {
repeat(5) {
ensureActive()
Thread.sleep(100)
println("step $it")
}
"finished"
}
println(result)
}
Now it stops after step 2 and prints null. A good habit for long loops is one
ensureActive() at the top of each pass.
Beware of catch (e: Exception) inside a coroutine. Since cancellation travels
as an exception, a catch-everything block catches it too, and quietly throws the
cancellation away:
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
runBlocking {
val job = launch {
repeat(5) {
try {
delay(100)
println("chunk $it")
} catch (e: Exception) {
println("chunk $it failed, trying the next one")
}
}
println("still here")
}
delay(250)
job.cancel()
println("cancelled")
}
chunk 0
chunk 1
cancelled
chunk 2 failed, trying the next one
chunk 3 failed, trying the next one
chunk 4 failed, trying the next one
still here
The task was cancelled and kept right on going. In a real program, this is the
download that won’t stop, or the screen that updates after it’s been closed. My
advice is to never catch Exception in coroutine code. Catch the specific thing you
expect, such as an IOException for a network error. If you truly must catch
everything, catch CancellationException first and throw it again, which is what
the Kotlin documentation tells you to do.
Several downloads, one deadline
Time to put the three answers together. The project is a pretend downloader: four
files downloading at the same time, a deadline for the whole batch, and an
optional broken connection. Nothing touches the network. Each “chunk” is a short
delay, so the timing is predictable and you can watch the structure work.
Make a folder, and save this as tasks.main.kts. You’ll also find it in
projects/kotlin, with a few extra things to try
at the bottom.
@file:DependsOn("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.11.0")
import kotlinx.coroutines.*
data class Download(val name: String, val chunks: Int, val msPerChunk: Long)
val downloads = listOf(
Download("notes.txt", 2, 100),
Download("photo.jpg", 4, 150),
Download("song.mp3", 5, 200),
Download("movie.mkv", 10, 250),
)
val deadline = args.getOrNull(0)?.toLong() ?: 1200
val broken = args.getOrNull(1)
suspend fun fetch(d: Download): Int {
var received = 0
try {
repeat(d.chunks) {
delay(d.msPerChunk)
received++
if (d.name == broken && received == d.chunks / 2) {
throw IllegalStateException("${d.name} lost its connection")
}
}
println("${d.name}: done")
return received
} finally {
if (received < d.chunks) {
println("${d.name}: stopped at $received of ${d.chunks}, partial file deleted")
}
}
}
runBlocking {
val start = System.currentTimeMillis()
try {
val total = withTimeoutOrNull(deadline) {
downloads.map { d -> async { fetch(d) } }.awaitAll().sum()
}
if (total == null) {
println("deadline of $deadline ms reached")
} else {
println("all $total chunks received")
}
} catch (e: IllegalStateException) {
println("gave up: ${e.message}")
}
println("finished in ${System.currentTimeMillis() - start} ms, nothing left running")
}
A script can read words typed after its name on the command line. They arrive in a
list called args. Here the first is the deadline in milliseconds, and the second
is the name of a file whose connection should break halfway.
Run it with the default deadline of 1,200 milliseconds:
kotlin tasks.main.kts
notes.txt: done
photo.jpg: done
song.mp3: done
movie.mkv: stopped at 4 of 10, partial file deleted
deadline of 1200 ms reached
finished in 1205 ms, nothing left running
The three small files made it. The movie was cancelled at the deadline, its
finally block cleaned up after it, and the program ended on time with nothing
left running.
Now give it three seconds:
kotlin tasks.main.kts 3000
Everything finishes, 21 chunks in about 2,500 milliseconds. One after the other, the same downloads would take 4,300 (add up each file’s chunks times its delay), so the overlap is doing its job. The batch takes as long as its slowest file.
Finally, break the song:
kotlin tasks.main.kts 3000 song.mp3
notes.txt: done
song.mp3: stopped at 2 of 5, partial file deleted
photo.jpg: stopped at 2 of 4, partial file deleted
movie.mkv: stopped at 1 of 10, partial file deleted
gave up: song.mp3 lost its connection
finished in 410 ms, nothing left running
When the song failed, its brothers and sisters were cancelled, every one of them
cleaned up, and only then did the error reach the catch at the top. Your exact
millisecond counts may differ by a few.
Look at where the concurrency lives in that file: one line, the map with async
inside withTimeoutOrNull. The scope around it is what guarantees that every
async it starts has finished, failed or been cancelled before the next line runs.
That’s all three questions answered by the shape of the code.
What’s left out
Dispatchers, which decide which threads your coroutines run on, are the next thing you’ll meet, especially for work that keeps the processor busy. Channels and Flow move streams of values between coroutines. Android adds scopes tied to screens, which cancel their work when the screen closes, so the structure you learned here runs right through an app. And there’s Gradle, Kotlin’s usual build tool, which a real project will hand you. You can mostly leave it alone and change only what you need.
When you’re ready for more, the Kotlin team’s own coroutines guide picks up from here, and the Kotlin documentation covers the rest of the language.
Ask the compiler what suspend means
You’ve been told that a suspend function can pause and pick up where it left off.
But the JVM underneath knows nothing about pausing. So where does the pausing
happen?
Put this in a file called Fetch.kt:
suspend fun fetch(): Int {
return 42
}
Compile it with kotlinc, which came with the kotlin command, and then look at
what it made with javap, a tool that came with Java:
kotlinc Fetch.kt -d out
javap -cp out FetchKt
Compare the function you wrote with the one javap describes. Count the
parameters. Check the return type. Then ask yourself what that extra parameter
might be carrying, and how a function could “pick up where it left off” if
someone handed it one.
Related
- Go: concurrency by message passing, with goroutines and channels.
- JavaScript:
asyncandawait, and code that waits for things to happen. - Java: exceptions, which carry both failures and cancellations here.
- Rust: values that might be missing, like Kotlin’s
Int?.
Tested with Kotlin 2.4.21 and kotlinx.coroutines 1.11.0, November 2026.
The Programming Shortcut: C#
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about value and reference semantics.
A big toolbox, and you need three tools
C# is a big language. Microsoft made it around 2000 for building large Windows programs, and it has been growing ever since. Today it runs servers, desktop apps, phone apps and a good share of the world’s video games. Every year it gains new features, and its documentation could keep you busy for a long winter.
You don’t need most of it. For this article you need three
words, struct, class and record, plus the humble = sign.
Those three words carry a question that every programming language answers: when I copy this, what do I get? Do you get a second, independent thing, or a second name for the same thing?
Most languages pick one answer for you and leave you to discover it, usually by accident, usually at an inconvenient hour. C# hands you the choice, out loud, every time you define a type. That makes it the best place to learn what a variable actually holds. Once you’ve seen it here, you’ll spot it in every language you meet.
What carries over
You already know most of what a C# program is made of. Here is how a few familiar things are spelled:
| What you know | lux | C# |
|---|---|---|
| a variable | var count = 0 | var count = 0; |
| printing | print("hi") | Console.WriteLine("hi"); |
| an array | [int] | int[], or List<int> for one that grows |
| a record | struct Point { x: int } | struct, class or record: the subject of this article |
| a value that might be missing | Option<int> | int? |
C# ends statements with semicolons and wraps blocks in braces. Loops, conditionals and functions look the way you’d guess. Read past them.
The fourth row is the interesting one. Where lux has one way to bundle named fields, C# has three. They look almost identical on the page, and they behave differently when you copy them.
Edit, save, watch it run
C# work runs through one command-line tool, dotnet, and it’s the only tool this
article uses. The steps below are for Windows, because that’s where C# feels most at home.
On Windows, one command installs it:
winget install Microsoft.DotNet.SDK.11
On macOS or Linux, follow Microsoft’s install guide; everything after this point is the same.
Make a new folder, and in it a file called app.cs with one line:
Console.WriteLine("Hello from C#");
Run it from a terminal in that folder:
dotnet run app.cs
The first run takes a few seconds while dotnet compiles your file, and then it
prints Hello from C#. There’s no project file and no Main function to write.
Statements at the top of the file run in order, the way a script would.
Now cut out the retyping:
dotnet watch run app.cs
dotnet watch runs your program, then waits. Every time you save the file, it
compiles and runs it again. Leave it running in one window, keep your editor in
another, and the rest of the article is three moves: edit, save, read the output.
Press Ctrl+C when you’re done.
Copy it, change the copy
Here’s the experiment that this article is built on. Make a point, copy it, change the copy, and look at both:
var a = new Point { X = 1, Y = 2 };
var b = a;
b.X = 99;
Console.WriteLine($"a.X is {a.X}, b.X is {b.X}");
struct Point
{
public int X;
public int Y;
}
A few small things to read past: new Point { X = 1, Y = 2 } builds a point and
sets its fields, public lets code outside the type see a field, and $"..." is
a string with values dropped into the braces. In a file like this one, type
definitions go after the statements that use them.
Save it, and the output reads a.X is 1, b.X is 99. Changing b left a alone.
That’s probably what you expected. If you learned lux, it’s what lux always did:
copy a struct and change the copy, and the original never noticed. In lux you
never had to ask “is this a copy?” In C#, you have to ask.
Now change one word. Make struct Point into class Point, and save:
var a = new Point { X = 1, Y = 2 };
var b = a;
b.X = 99;
Console.WriteLine($"a.X is {a.X}, b.X is {b.X}");
class Point
{
public int X;
public int Y;
}
This time it prints a.X is 99, b.X is 99. You changed b, and a changed too.
Same fields, same assignment, same line of output code. One word was different.
What’s in the box
Think of a variable as a labeled box. The question is what goes in the box.
A struct is a value type. The box holds the value itself: the X and the Y,
right there inside the variable. int, double, bool and char are value types
too. When you write var b = a, C# copies the contents of a’s box into b’s
box. Now there are two points, and they have nothing to do with each other.
A class is a reference type. When you write new Point, C# builds the object
somewhere else in memory, in an area the runtime manages for you called the
heap, and hands you back a reference: a small value that says where the object
lives. The box holds the reference, not the point. When you write var b = a, C#
copies the contents of a’s box into b’s box, just as before. But the contents
are a reference, so now two boxes refer to one point.
struct: a [ X=1 Y=2 ] b [ X=99 Y=2 ] two points
class: a [ ref ]──┐
├──> { X=99 Y=2 } one point
b [ ref ]──┘
So here is the rule: assignment always copies the box, and the type decides what’s in the box. C# never quietly skips the copy. When the box holds a value, you get a second value. When it holds a reference, you get a second reference to the same object.
Two names for one object is called aliasing, and it’s neither good nor bad on its own. It’s how a program shares things. If three parts of your program need the same customer record, you want them all looking at one record, so that a change made by one is seen by all. If you meant to take a snapshot, aliasing is a bug.
How a reference is stored in the machine, and what a pointer really is, belong to the C article. For this one, “where the object lives” is enough.
Functions get a copy of the box too
Calling a function is an assignment in disguise. Each parameter is a new box, and the argument’s contents are copied into it. The same rule applies, so the same two outcomes follow:
var p = new Point { X = 1 };
Shift(p);
Console.WriteLine($"after Shift: {p.X}");
Replace(p);
Console.WriteLine($"after Replace: {p.X}");
void Shift(Point q)
{
q.X += 10;
}
void Replace(Point q)
{
q = new Point { X = 500 };
}
class Point
{
public int X;
}
This prints after Shift: 11 and then after Replace: 11.
Shift got a copy of the reference, followed it to the one shared point, and
changed it. The caller sees the change. Replace got a copy of the reference too,
and then overwrote its own box with a reference to a brand-new point. That changed
q, the function’s box, and never touched p, the caller’s box. The new point
with 500 in it is dropped when the function ends.
Change class to struct and save. Now both lines print 1, because Shift
changed its own private copy of the point.
This trips up programmers in every language that works this way, and most mainstream languages do. You can change the object a parameter refers to. You can’t change which object the caller’s variable refers to.
Unless you ask. C# has a keyword for handing a function the caller’s box itself instead of a copy of its contents:
var p = new Point { X = 1 };
Replace(ref p);
Console.WriteLine($"after Replace: {p.X}");
void Replace(ref Point q)
{
q = new Point { X = 500 };
}
class Point
{
public int X;
}
Now it prints 500. With ref, q is another name for the variable p, so
writing to q writes to p. You have to say ref in both places, at the
definition and at the call, so nobody gets surprised. Notice that this is a
separate idea from reference types. A reference type puts a reference in the
box. Passing by reference hands over the box. The words overlap, and the ideas
don’t, which is why ref works on structs too.
Arrays and lists are references
Here’s where people coming from lux get caught. In C#, arrays are reference types,
and so is List<T>:
int[] scores = [70, 85, 90];
var backup = scores;
backup[0] = 0;
Console.WriteLine($"scores[0] is {scores[0]}");
var copy = scores.ToArray();
copy[1] = 0;
Console.WriteLine($"scores[1] is {scores[1]}");
The first line prints scores[0] is 0. Naming your variable backup didn’t make
it one. ToArray() builds a new array with the same contents, and changing that
one leaves scores alone, so the second line prints scores[1] is 85.
What about a struct that contains an array or a list? Copying a struct copies its box, and only its box. A list field holds a reference, so the copy gets the reference, and both structs share one list:
var mine = new Hand { Owner = "me", Cards = ["ace"] };
var yours = mine;
yours.Owner = "you";
yours.Cards.Add("king");
Console.WriteLine($"{mine.Owner} holds {string.Join(", ", mine.Cards)}");
struct Hand
{
public string Owner;
public List<string> Cards;
}
This prints me holds ace, king. The owner was copied, so it stayed me. The list
wasn’t copied, so the king turned up in both hands. A copy that copies only the top
layer is called a shallow copy, and assignment in C# is always shallow. If you
want the list copied too, you write that yourself.
Strings are a curious case. string is a reference type, yet you’ll never catch two
string variables sharing a change. That’s because no C# string can be changed.
name + "!" builds a new string and leaves the old one alone. When nothing can
change an object, sharing it is harmless, and a reference to it behaves like a
value. Hold on to that; it comes back in a moment.
What does “the same” mean?
Copying has a twin question: when are two things equal?
For a class, == asks whether two references point to the same object. It’s
called reference equality, or identity. Two points with the same X and Y, made by
two separate news, are not ==:
var a = new Point { X = 1 };
var b = new Point { X = 1 };
var c = a;
Console.WriteLine(a == b);
Console.WriteLine(a == c);
class Point
{
public int X;
}
That prints False, then True: a and c are two boxes holding one reference. For a struct, the natural question would be
whether the fields match, but C# won’t guess. A plain struct has no == at all
until you write one:
var a = new Point { X = 1 };
var b = new Point { X = 1 };
Console.WriteLine(a == b);
struct Point
{
public int X;
}
The compiler stops with error CS0019: operator == cannot be applied to two
Points. (a.Equals(b) works, and compares the fields.)
This is where the third word, record, comes in. A record is a type the
compiler fills with code that treats it as nothing but its data. You declare its fields in one line:
var a = new Point(1, 2);
var b = new Point(1, 2);
Console.WriteLine(a == b);
var c = a with { X = 99 };
Console.WriteLine($"{a} and {c}");
record Point(int X, int Y);
That prints True, then Point { X = 1, Y = 2 } and Point { X = 99, Y = 2 }.
A record is a class, so a and b hold references to two separate objects. But
the compiler wrote an == for it that compares the fields, which is called value
equality. Its fields can’t be changed after it’s made, so instead of changing a,
you write a with { X = 99 } and get a new record, a copy with one field
different. a is still 1, 2.
Remember the strings? A record is the same trick: a reference type that nobody can
change. It’s shared, and the sharing can’t hurt you, so it behaves like a value.
There’s also record struct, a value type with the same conveniences, for when you
want the box itself to hold the data.
So C# gives you four combinations, and you pick one each time you write a type:
| You write | Copying gives you | == asks |
|---|---|---|
struct | a second, independent value | nothing, until you write it |
class | a second reference to the same object | “same object?” |
record | a second reference, but nobody can change the object | “same fields?” |
record struct | a second, independent value | “same fields?” |
The same question, everywhere
Here is what you can take to any language you meet: if I copy this and change the copy, what happens to the original? Every language has an answer, and now you know what to look for.
| Language | What a variable holds |
|---|---|
| lux | always a value; a copy is always yours |
| C | always a value; you make references by hand, as pointers (C) |
| Swift | the same split as C#: structs are values, classes are references (Swift) |
| Go | structs and arrays are values; slices and maps share what they hold |
| Java | numbers, characters and booleans are values; every object is a reference |
| Python | always a reference; numbers and strings can’t change, so they act like values |
| JavaScript | numbers and strings act like values; objects and arrays are references |
Look at Python, Java and JavaScript. They never ask you to choose, and they all work like C#’s classes: pass an object to a function, and the function can change your object. When an experienced programmer in one of those languages says “be careful, that list is shared,” this is what they mean.
What a class gives up
lux made you a promise: whatever you copy is yours. Nobody else can change it. C#’s classes give that promise up. Any part of the program that holds a reference to your object can change it while you aren’t looking, and you’ll find out when you next read it. That’s the price of sharing, and in a large program it’s a real price: “who else has a reference to this?” can be a hard question to answer.
References bring one more thing lux didn’t have: a reference can point to nothing.
That’s null, and it gets an article of its own (Java). C# warns you
when a null might slip into a variable that shouldn’t hold one, and the ? in
Point? says that one may.
Beware of changing a struct you can’t see. Structs get copied in places you
don’t expect, and a change made to a copy disappears without a word. Put a
struct in a List, and list[0] hands you a copy:
var counters = new List<Counter> { new Counter() };
counters[0].Add();
Console.WriteLine(counters[0].Count);
struct Counter
{
public int Count;
public void Add() => Count++;
}
This prints 0. Add ran, on a copy that vanished at the end of the line. The
compiler does catch the plain case, counters[0].Count = 5, with error CS1612
(“Cannot modify the return value… because it is not a variable”), but it can’t
see what a method does. My rule: change a struct only through a variable you
named yourself, never through a list, a property or another object’s field. If
that rule is hard to keep, declare a readonly struct, which the compiler refuses
to change anywhere, and replace it instead of changing it. And when you can’t decide between struct and class,
pick class or record. A struct suits something small that acts like a single
value: a point, a color, an amount of money.
An undo that remembers
Undo is the classic place where value semantics matter. To undo, you keep a history of where you’ve been, and each entry in that history had better be a snapshot, not a second name for where you are now.
The project is one file, undo.cs, in
projects/csharp/. A marker starts at (0,0) and
follows a string of moves: N, S, E and W step one square, and u undoes the last
step. Before each step, the current spot goes onto a stack (a list you add to and
take from at the same end). Undo takes the top one back off.
Here is its heart:
history.Push(here);
switch (move)
{
case 'N': here.Y += 1; break;
case 'S': here.Y -= 1; break;
case 'E': here.X += 1; break;
case 'W': here.X -= 1; break;
}
And Spot is a struct with an X and a Y. Put the file in a folder of its own and
start the watcher:
dotnet watch run undo.cs
It prints the spot and the history after every move:
N at (0,1) history: (0,0)
N at (0,2) history: (0,1) (0,0)
E at (1,2) history: (0,2) (0,1) (0,0)
u at (0,2) history: (0,1) (0,0)
E at (1,2) history: (0,2) (0,1) (0,0)
u at (0,2) history: (0,1) (0,0)
u at (0,1) history: (0,0)
S at (0,0) history: (0,1) (0,0)
Every undo steps back one square. Push(here) copied the spot into the stack, so
when here moved on, the copy stayed put.
Now, with dotnet watch still running, change struct Spot to class Spot and
save. The first four lines:
N at (0,1) history: (0,1)
N at (0,2) history: (0,2) (0,2)
E at (1,2) history: (1,2) (1,2) (1,2)
u at (1,2) history: (1,2) (1,2)
The history is full of the current spot, and undo does nothing. There was only
ever one Spot object. Every Push(here) put another reference to it on the
stack, and every move changed the one object they all refer to. The history was a
list of aliases.
Before you change it back, open the file and read the “Try this next…” block at the bottom. It walks you through two ways to fix the class version, and one way the struct version can still share more than you’d think.
What this article leaves out
C# quietly converts a value type to a reference when you store it as a
plain object, which is called boxing, and it has its own surprises. Where each kind
of value lives in memory, and how the garbage collector clears away objects nobody
refers to any more, got a sentence here and deserve more. in and out parameters,
ref return values and Span<T> are refinements of the box idea for programs that
care about speed. Inheritance and interfaces, the other half of what classes do,
are another article’s subject (Swift teaches the interface idea).
C# 15’s new union types, which combine existing types into one, are C#’s
version of sum types, whose home is the Rust article.
When you want the full language, Microsoft’s C# documentation starts with a tour and works up. Its guide to choosing between class and struct is short and gives the same advice as the warning above. It dates from 2008, and it says “passed by reference” where this article would say “a copy of the reference is passed”, which you can now see is a different thing.
Ask the compiler what it wrote
You’ve seen that a record gets an == you never wrote. Ask the compiler what else
it wrote. Make a new file with these two lines and run it:
foreach (var member in typeof(Cat).GetMembers()) Console.WriteLine(member);
record Cat(string Name);
You’ll find op_Equality (that’s the ==), an Equals, a Deconstruct and a
method with the odd name <Clone>$. What is that clone for? Then change record
to record struct, save, and look for it again. Why would a struct not need one?
Related
- C: what a reference really is in memory, and pointers you manage yourself.
- Swift: structs as values on the way to protocols and generics.
- Java:
null, the reference that points to nothing. - Rust: sum types, the idea behind C# 15’s
union.
Tested with .NET 11.0.100 and C# 15, November 2026.
The Programming Shortcut: Java
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about null and exceptions.
Java got small while nobody was looking
Java has a reputation. Ask around and you’ll hear about public static void main,
classes named AbstractSingletonProxyFactoryBean, and build files longer than the
program they build. Some of that was earned, twenty years ago.
Here is a complete Java program today:
void main() {
IO.println("Hello");
}
That’s it. No class to declare, nothing to import, no build tool. Save it in a file and run it.
Meanwhile, Java became the language a large share of the world’s servers run on: banks, airlines, shops, the back ends of apps on your phone. It stayed there by rarely breaking old code, which is why Java’s oldest design decisions are alive and well in a language that otherwise feels modern.
Two of those decisions are what this article is about. They are Java’s answers to two questions every program has to answer, over and over: what if the value I need isn’t there? and what if the thing I asked for couldn’t be done?
Java answers the first with null and the second with exceptions. Neither answer shows up in the types the way you might expect. So Java is a fine place to learn what programming without a safety net is like, and the habits that let you do it well anyway. Those habits travel to Python, JavaScript, and anywhere else a value might quietly be missing.
What you can skip
You already know most of what a Java program is made of. The interesting rows are the first two, and they’re where the rest of this article lives.
| What you know | lux | Java |
|---|---|---|
| a value that might be missing | Option | any object can be null; Optional by convention |
| an operation that might fail | Result | exceptions, some of them checked |
| a struct | struct | record |
functions, loops, if, arrays | the same ideas | the same ideas, in C-style braces |
If you learned lux, those first two rows are the story in miniature. lux’s
Option and Result were a safety net: the type itself said “this might be
missing” or “this might fail”, and match wouldn’t let you ignore it. Java has no
such net under most of its code. What it has instead is a set of habits, and the
habits are worth more than any one language’s syntax.
Edit, then java Main.java
You need a Java Development Kit (JDK), version 25 or later. The free builds at
adoptium.net install like any other program. When
java -version prints 25 or higher, you’re set.
Make a folder, and in it a file called Main.java:
void main() {
String name = "Java";
IO.println("Hello from " + name + " " + Runtime.version().feature());
}
Then run it:
java Main.java
Hello from Java 25
Everything in this article runs that way: edit Main.java, save, run
java Main.java. The java command compiles your file in memory, checks it, and
runs it, all in one step. A file written this way, with no class around it, is
called a compact source file. Java treats it as a class it writes for you, and
it brings the standard library’s everyday parts (lists, maps, files) into scope
without any import lines. IO.println prints a line.
Keep that terminal open. Every snippet below is a whole program you can paste over
Main.java and run.
Two kinds of bad news
Before any Java, the idea itself.
A program gets bad news in two shapes. Sometimes a value simply isn’t there: you look up a word in a dictionary and it’s not in it; a form field was left blank; a customer has no middle name. Nothing went wrong. Missing is a perfectly normal answer.
Other times an operation couldn’t be done: the file you asked to read doesn’t exist, the text you asked to turn into a number says “seven”, the network went away halfway through. Something did go wrong, and there’s usually a reason worth reporting.
Languages differ in where they put this news.
Some put it in the type. In Rust, a function that might not find something
returns an Option, a value that is either “here it is” or “nothing”, and you
can’t use what’s inside without first saying what happens when there’s nothing.
(The Rust article is the home of Option and its sibling Result, the
same idea for failures.) The compiler checks that every caller deals with the bad
news, so the net catches you before the program ever runs.
Java puts most of it outside the type. A missing value is null, a special
value that any object variable can hold. A failure is an exception, which leaves
the normal flow of your program entirely. The types in your code mostly don’t
mention either, and the compiler mostly doesn’t check.
That’s the safety net gone. Let’s see what falls through it, and then what careful Java programmers do about it.
Null: the value that isn’t one
In Java, variables come in two kinds. The primitive types, such as int,
double and boolean, hold their value directly, and they can never be null. An
int is always some number. Everything else is a reference type: a String, a
List, a Map, your own records. A variable of a reference type holds a
reference to an object somewhere in memory, the way a phone number refers to a
phone. And any reference can be null, meaning it refers to nothing at all.
So a variable declared as String holds either a string or null. The type
doesn’t say which, and the compiler doesn’t ask.
Where do nulls come from? Mostly from code that needs a way to say “not found”.
Java’s Map (a dictionary: keys in, values out) is the classic source. Ask it for
a key it doesn’t have, and it hands you null:
void main() {
Map<String, String> capitals = new HashMap<>();
capitals.put("France", "Paris");
capitals.put("Japan", "Tokyo");
String capital = capitals.get("Peru");
IO.println("Peru's capital has " + capital.length() + " letters");
}
(The <String, String> part says the map’s keys and values are both strings. Java
calls that generics, and the Swift article is where the series
explains them. Here you can read it as a label.)
This compiles without a murmur. Then it runs, and stops:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.length()" because "<local2>" is null
at Main.main(Main.java:7)
A NullPointerException, known to every Java programmer as an NPE, is what
happens when you treat null as if it were an object: call a method on it, read a
field from it. Modern Java tells you which value was null and on which line, which
is more help than it used to give. (<local2> is your variable capital. When
java compiles a file on the fly, it numbers local variables instead of keeping
their names.)
Notice where the program stopped. Not at get, where the missing value came from,
but at length(), where it was used. In this snippet those are one line apart. In
a real program they can be in different files, written by different people, run
minutes apart.
Null travels
That gap between where a null is born and where it bites is the real trouble with null. Here it is stretched out a little:
record Contact(String name, String email) {}
String domainOf(Contact contact) {
String email = contact.email();
return email.substring(email.indexOf('@') + 1);
}
void main() {
List<Contact> contacts = List.of(
new Contact("Ana", "ana@example.com"),
new Contact("Ben", null),
new Contact("Cy", "cy@example.org"));
for (Contact contact : contacts) {
IO.println(contact.name() + " is at " + domainOf(contact));
}
}
Ana is at example.com
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "String.indexOf(int)" because "<local2>" is null
at Main.domainOf(Main.java:5)
at Main.main(Main.java:15)
Ben was created with no email on line 11. Nothing complained. The record held the
null, the list held the record, the loop handed it to domainOf, and only there,
inside a function that was written correctly, did the program fall over. The error
points at domainOf, but domainOf isn’t where the mistake is.
That’s why Tony Hoare, who added null references to a language called ALGOL W in 1965, later called them his “billion-dollar mistake”. The problem isn’t that a value can be missing. Missing values are real. The problem is that the missing value looks just like a present one until the moment you touch it.
Habit one: decide at the door
The first habit is to deal with null where it enters your program, and nowhere else. Every value comes in through some door: a map lookup, a file, a user’s answer, another library. Right there, decide what missing means. Use a default, skip the item, report a problem. Then everything past the door can trust its values.
For a map, the door is the lookup itself, and Map has a method built for it:
void main() {
Map<String, Integer> stock = Map.of("apples", 12, "pears", 0);
for (String fruit : List.of("apples", "pears", "plums")) {
int count = stock.getOrDefault(fruit, 0);
IO.println(fruit + ": " + count);
}
}
apples: 12
pears: 0
plums: 0
getOrDefault answers the “what if it’s missing?” question on the spot, so count
is a plain int, and an int can never be null.
Habit two: fail at the door
Sometimes missing isn’t a normal answer. A contact with no email might simply be a bug. Then you want the program to stop, but at the door, where the bug is, not three functions later.
Java’s Objects.requireNonNull does that. It hands back its argument if it isn’t
null, and throws an NPE straight away if it is. Records let you run a check like
this every time one is made, in a compact constructor: a block named after the
record that runs before the fields are filled in.
record Contact(String name, String email) {
Contact {
Objects.requireNonNull(email, "email is required");
}
}
void main() {
var ana = new Contact("Ana", "ana@example.com");
IO.println(ana);
var ben = new Contact("Ben", null);
IO.println(ben);
}
Contact[name=Ana, email=ana@example.com]
Exception in thread "main" java.lang.NullPointerException: email is required
at java.base/java.util.Objects.requireNonNull(Objects.java:246)
at Main$Contact.<init>(Main.java:3)
at Main.main(Main.java:10)
Same crash, much better place. Line 10 is the line that made Ben, so the error now points at the cause instead of an innocent bystander. This is called failing fast, and it turns a mystery into a typo.
Habit three: say “maybe” out loud
The third habit is for functions you write. If your function might have nothing to
return, don’t return null and hope the caller remembers. Return an Optional.
Optional<String> is a box that either holds a string or is empty, and Java has
had it since version 8. If you’ve used an Option or Maybe type, this is
Java’s version. The difference is that nothing forces anyone to use it. It’s a
convention, and Java’s own documentation says what it’s for: a method’s return
type, where there may be “no result” and a null would likely cause errors.
Map<String, String> capitals = Map.of("France", "Paris", "Japan", "Tokyo");
Optional<String> capitalOf(String country) {
return Optional.ofNullable(capitals.get(country));
}
void main() {
for (String country : List.of("France", "Peru")) {
String answer = capitalOf(country)
.map(city -> city + " (" + city.length() + " letters)")
.orElse("not in my list");
IO.println(country + ": " + answer);
}
}
France: Paris (5 letters)
Peru: not in my list
Optional.ofNullable is a door: it turns a possible null into a box that might be
empty. map works on what’s inside if there’s anything there (the city -> ...
part is a small unnamed function, a lambda). orElse says what to use when the
box is empty. Nowhere in that chain can you call .length() on nothing.
The methods are handy, but the return type matters more. A caller who
reads Optional<String> capitalOf(String country) knows, before running anything,
that the answer might be missing. A String return type can’t tell them that.
Exceptions: bad news that leaves the room
Now the other kind of bad news: the operation that couldn’t be done.
What should a function that turns text into a number do when the text is “seven”? In lux, parseInt returns an Option,
and the caller matches on it. Java’s Integer.parseInt returns a plain int. And
there is no int that means “that wasn’t a number”. So it does something else:
void main() {
int age = Integer.parseInt("seven");
IO.println("Next year you'll be " + (age + 1));
}
Exception in thread "main" java.lang.NumberFormatException: For input string: "seven"
at java.base/java.lang.NumberFormatException.forInputString(NumberFormatException.java:67)
at java.base/java.lang.Integer.parseInt(Integer.java:565)
at java.base/java.lang.Integer.parseInt(Integer.java:662)
at Main.main(Main.java:2)
It throws an exception. An exception is an object that describes what went
wrong, and throwing it means abandoning the current function right there. No
return value, no next line. Java leaves that function, then the function that
called it, then the one that called that, until it finds code that has said “I
can handle this kind of problem”. If it never finds any, the program ends and
prints the list you see above, called a stack trace: every function that was
in the middle of running, innermost first. Read it from the top until you reach
your own code. Main.java:2 is the line to look at.
Code that handles an exception catches it, with try and catch:
int readAge(String text) {
return Integer.parseInt(text.strip());
}
int ageNextYear(String text) {
return readAge(text) + 1;
}
void main() {
for (String answer : List.of("41", " 29 ", "seven")) {
try {
IO.println(answer + " -> " + ageNextYear(answer));
} catch (NumberFormatException e) {
IO.println(answer + " -> not an age: " + e.getMessage());
}
}
}
41 -> 42
29 -> 30
seven -> not an age: For input string: "seven"
Look at ageNextYear. It calls readAge, which can fail, and it does nothing
about it. It doesn’t need to. When “seven” comes along, the exception flies out of
parseInt, out of readAge, out of ageNextYear, and lands in the catch in
main. The functions in between never knew.
This cuts both ways. The good side: code in
the middle stays clean. It deals with the normal case and lets failures pass
through to whoever is in a position to do something about them. The other side:
looking at ageNextYear, you can’t tell that it might not return at all. The
failure is invisible in its type, just like null was.
Habit four: catch where you can act
That suggests the fourth habit. Catch an exception in the place that knows what to do about it, not in the place where it happened.
readAge can’t do anything useful with “seven”. It doesn’t know whether to ask
again, use a default or give up, because it doesn’t know who’s asking. main
knows. It’s printing answers, so it can print “not an age” and carry on with the
next one. A good catch is close to a decision: skip this line, try again, tell the
user, use the backup. If you can’t name the decision, you’re in the wrong place to
catch.
The part of the net Java kept
All of that is true of the exceptions you’ve seen so far, which Java calls unchecked. But Java has a second kind, and here the compiler does step in.
Reading a file can fail for reasons no amount of careful coding prevents: the
file was deleted, the disk is full, you don’t have permission. Java’s designers
decided failures like these should be impossible to forget, so they made them
checked exceptions. If a method can throw one, its signature says so, with the
word throws. And any code that calls it must either catch the exception or
declare it too, passing the news upward on purpose.
Files.readString reads a whole file into a string, and it’s declared
throws IOException. Call it without saying what happens on failure:
void main() {
String notes = Files.readString(Path.of("notes.txt"));
IO.println(notes);
}
Main.java:2: error: unreported exception IOException; must be caught or declared to be thrown
String notes = Files.readString(Path.of("notes.txt"));
^
1 error
error: compilation failed
This time nothing ran. The compiler refused, just like a language with a Result
type would. Make the decision, and it’s happy:
void main() {
try {
String notes = Files.readString(Path.of("notes.txt"));
IO.println(notes);
} catch (IOException e) {
IO.println("No notes yet (" + e + ")");
}
}
No notes yet (java.nio.file.NoSuchFileException: notes.txt)
The catch caught a NoSuchFileException, though it asked for an IOException.
Exceptions come in families, and catching a family catches all its members.
(NumberFormatException belongs to a family called RuntimeException, which is
what makes it unchecked.)
So Java’s net has one strand left: the failures that come from the outside world. Everything else, including every null, falls straight through.
Against the grain
If you’re used to a language with Option and Result, Java asks you to give up
a guarantee you may not have noticed you were relying on: a type tells the
truth. In Java, a String might not be a string, and a method that returns an
int might not return at all. The compiler checks that your types fit together.
It doesn’t check that the values are there.
Several languages that grew up in Java’s shadow closed that gap. Kotlin, C# and
Dart all let you write String? for “a string or null”, and plain String then
means a string. Each of them checks, before anything runs, that you dealt with the
? (Kotlin and Dart with errors, C# with warnings). The Kotlin and
C# articles touch on it along the way. In Java, the checking is your job, and the four habits are how you do it.
Beware of the empty catch block. Sooner or later the compiler will demand you handle a checked exception you don’t care about, and you’ll be tempted to write this:
try { settings = Files.readString(path); } catch (IOException e) { }It compiles, and the error goes away, along with every clue to what happened.
settingskeeps whatever it held before, quite likely null, and some other line, far away, will throw an NPE about it next week. This is the worst thing you can do with an exception, worse than not catching it at all, because an uncaught exception at least tells you what went wrong and where. If you truly can’t act on it, don’t catch it: addthrows IOExceptionto your method and let the news travel up to someone who can. And if you catch it, do something you could describe out loud.
A small project: is there enough for pancakes?
Time to put the habits together. The program reads a list of what’s in your pantry, then checks whether you have enough of everything a recipe needs. The pantry file is the outside world, so it’s where the trouble comes in: the file might be missing, a line might have no amount, an amount might not be a number, and the recipe might ask for something the pantry never mentions.
Make a new folder. In it, save this as pantry.txt, blank line and all:
flour, 500
eggs, 6
milk, about a liter
sugar, 200
butter
And save this as Main.java next to it:
record Need(String item, int amount) {}
List<Need> pancakes = List.of(
new Need("flour", 200),
new Need("eggs", 2),
new Need("milk", 300),
new Need("butter", 30));
void main() {
Map<String, Integer> pantry;
try {
pantry = readPantry(Path.of("pantry.txt"));
} catch (IOException e) {
IO.println("Can't read the pantry: " + e);
return;
}
boolean ready = true;
IO.println("Pancakes need:");
for (Need need : pancakes) {
String verdict = amountOf(pantry, need.item())
.map(have -> have >= need.amount() ? "ok" : "short by " + (need.amount() - have))
.orElse("missing");
IO.println(" " + need.item() + " " + need.amount() + ": " + verdict);
if (!verdict.equals("ok")) {
ready = false;
}
}
IO.println(ready ? "Get the pan out." : "Not yet. Time for a shopping list.");
}
Map<String, Integer> readPantry(Path file) throws IOException {
Map<String, Integer> pantry = new HashMap<>();
List<String> lines = Files.readAllLines(file);
for (int i = 0; i < lines.size(); i++) {
String line = lines.get(i).strip();
if (line.isEmpty()) {
continue;
}
String[] parts = line.split(",");
if (parts.length != 2) {
IO.println("line " + (i + 1) + " skipped: no amount in \"" + line + "\"");
continue;
}
try {
pantry.put(parts[0].strip(), Integer.parseInt(parts[1].strip()));
} catch (NumberFormatException e) {
IO.println("line " + (i + 1) + " skipped: \"" + parts[1].strip() + "\" is not a number");
}
}
return pantry;
}
Optional<Integer> amountOf(Map<String, Integer> pantry, String item) {
return Optional.ofNullable(pantry.get(item));
}
The file in the series’ repository, projects/java/Main.java, has the same code
plus a block of “Try this next…” ideas at the end. Run it from that folder:
java Main.java
line 3 skipped: "about a liter" is not a number
line 6 skipped: no amount in "butter"
Pancakes need:
flour 200: ok
eggs 2: ok
milk 300: missing
butter 30: missing
Not yet. Time for a shopping list.
Every kind of bad news in the program has one place where it’s handled, and each place makes a decision.
The missing file is a checked exception. readPantry can’t do anything about it,
so it declares throws IOException and passes it up. main catches it, because
main knows what to do: say so and stop. Try it. Rename pantry.txt and run
again.
The line butter has no amount. That’s missing data, not a failure, so it’s
handled with a plain if, right where the line is read. The blank line is
missing data too, and it’s skipped the same way.
“about a liter” is a failure: parseInt throws. It’s caught inside the loop,
because that’s where the decision lives. One bad line shouldn’t cost you the rest
of the file, so the loop reports it and moves on.
And the recipe’s lookups go through amountOf, the one door between the map’s
nulls and the rest of the program. Its return type, Optional<Integer>, tells
main that an item might not be there, and orElse("missing") is where main
answers. No variable in main is ever null.
Now edit pantry.txt. Fix the milk line, give the butter an amount, run again.
Then break it in a new way of your own and see which door catches it.
What’s left out, and where to go next
You haven’t met finally, or try-with-resources, Java’s way
of making sure a file or a connection is closed even when an exception flies past.
You haven’t written your own exception classes, or seen how one exception can
carry another as its cause. You haven’t met the annotations (such as @Nullable)
and outside checkers that some teams use to bolt null checking onto Java. And
you’ve skipped almost all of Java itself: classes, interfaces, inheritance, the
standard library, concurrency. Those are the language. This article was about one
idea.
When you go looking for more, start at dev.java/learn,
the learning site run by the Java team at Oracle. Be a little wary
of older tutorials that open with Maven, Spring or a ten-line public static void main before you’ve written anything. They aren’t wrong, but they solve problems
you don’t have yet, and java Main.java will take you a long way first.
Try this
Java comes with a place to try anything one line at a time. It’s called jshell,
and it was installed with your JDK. Type jshell, then /help.
Then bring it this question: what’s the difference between missing and failing?
Type Map.of("a", 1).get("b") and see what comes back. Then
Integer.parseInt("b"). Then Optional.ofNullable(null). One answers with
nothing, one refuses to answer, and one answers with a box that says so.
/exit when you’re done.
Related
- Rust is the home of
OptionandResult, the safety net this article does without, built into the types. - Kotlin, C# and Dart write a value that
might be missing as
T?, and check it before the program runs. - Swift explains generics, the
<String, Integer>labels on Java’s maps and lists.
Tested with JDK 25.0.5.1 LTS (Temurin), November 2026.
The Programming Shortcut: C
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about memory, and the data structures built on it.
C does what you say, and nothing more
Every language you have used sits on top of the same thing: a long row of bytes in your computer’s memory. Python, JavaScript, Java and lux all keep that row out of sight. They decide where your values go, how much room each one gets, and when the room can be given back. Most days that’s a gift.
C was made in the early 1970s to write an operating system, and it was made by people who needed to see the row. So C is a thin layer over the machine. It hands you the bytes, tells you where they are, and steps back. It doesn’t check that you stayed inside your array. It doesn’t clean up after you. It does what you say, and nothing more.
That sounds like bad news, and for a big program written in a hurry it can be. For learning, it’s good news. The languages you’ll use after this are built on the things C shows you directly: addresses, blocks of bytes, the stack and the heap. Once you’ve seen them, a lot of behavior that used to feel like magic turns into plain bookkeeping. Why does a list in Python grow without being told to? Why does changing an object inside a function sometimes change it outside, too? Why do some languages need a garbage collector? The answers are all in the row.
This article is about memory: how your data lives in the machine, and the data structures you build out of it. C is the vehicle, and we’ll use only as much of it as the idea needs.
What carries over
You already know most of C’s shape. Its loops, conditionals, functions and structs look like the ones you know, because a great many languages copied them from C. The rows below are the ones that change.
| What you know | lux | C |
|---|---|---|
| a record | struct | struct, laid out field by field in memory |
| an array | [int], knows its length | a row of values; the length is yours to remember |
| a growable list | queue += 4 | doesn’t exist; you build it (the project below) |
| text | string | an array of bytes ending in a zero byte |
| a value that might be missing | Option | a pointer that might be NULL |
| errors you expect | Result | a return value you agree to check |
| memory | handled for you | malloc to get it, free to give it back |
If you learned lux first, here’s the bridge: lux managed memory for you every time you made a struct or added to an array. This article shows what it was doing.
(Option is a way of saying “there may be no value here” that the compiler makes
you check; its home in this series is the Rust article. C’s version is a
pointer that might be NULL, an address that means “nothing here”, and nothing makes
you check it.)
Compile, run, read the warnings
C is compiled: a program called a compiler turns your text file into a program your machine runs directly. The compiler here is GCC, the GNU Compiler Collection. I’ll use Linux, because that’s where GCC is at home. On Debian or Ubuntu, one command installs it:
sudo apt install gcc
Elsewhere, start from GCC’s install page. (A Mac’s
own gcc is really a different compiler, Clang, and it takes the same command.)
Make a file called where.c:
#include <stdio.h>
int main(void) {
int score = 75;
printf("score is %d\n", score);
printf("it lives at %p\n", (void *)&score);
printf("it takes %zu bytes\n", sizeof score);
}
Then compile it and run it:
gcc -std=c23 -Wall -Wextra -Werror -fsanitize=address,undefined -g -o where where.c && ./where
That’s a long command, and every piece of it is there to help you. -std=c23 asks
for the current version of the language, C23. -Wall and -Wextra turn on the
compiler’s warnings, and -Werror turns every warning into an error, so a warning
stops the build instead of scrolling past. -fsanitize=address,undefined builds two
sanitizers into your program: extra checking code that watches its memory use and
arithmetic while it runs, and stops with a report when something goes wrong. -g
keeps your line numbers in the program, so those reports can point at your code. -o where names the result, and ./where runs it.
You’ll see something like this:
score is 75
it lives at 0x7ff3ff500020
it takes 4 bytes
Your address will be different, and it’ll change from run to run. From here on you’ll work the same way: edit, compile with that one command, read what the compiler says, run. Put the command in your shell history and press the up arrow.
Memory is a long row of numbered boxes
Picture your program’s memory as one very long row of boxes. Each box holds one byte, a number from 0 to 255. Each box has a number of its own, counting up from the start of the row. That number is the box’s address.
Every variable you’ve ever made lives in some of those boxes. score in the program
above takes 4 of them, starting at the address it printed. Two operators let you ask
about this:
sizeof x tells you how many bytes x takes. It comes back as a size_t, the type
C uses for sizes, which printf prints with %zu.
&x gives you the address of x: where its first byte lives. printf prints an
address with %p, and the (void *) in front says “this is just an address”, which
is what %p asks for.
So what does a type mean, down here? A type is two facts: how many boxes, and how to
read the numbers in them. An int is four boxes read together as one whole number.
You can see the four boxes for yourself by reading the same address as plain bytes:
#include <stdio.h>
int main(void) {
int n = 258;
unsigned char *bytes = (unsigned char *)&n;
for (size_t i = 0; i < sizeof n; i++) {
printf("box %zu holds %d\n", i, bytes[i]);
}
}
On a typical laptop that prints 2, 1, 0 and 0. The number 258 is one 256 plus 2, and the machine stores it smallest part first. Nothing about the boxes says “this is an int”. The type lives in your program, and the row just holds numbers.
A pointer is an address you keep
That bytes variable above was a pointer: a variable whose value is an address.
You write its type with a star, so int *p is “a pointer to an int”, and you follow
it with a star too: *p means “the value at the address in p”.
Here’s why that matters. When you call a function in C, it gets a copy of each argument. A function that tries to swap two numbers it was handed swaps its own copies and changes nothing outside. Hand it the addresses instead, and it can reach back into the caller’s boxes:
#include <stdio.h>
void swap(int *a, int *b) {
int held = *a;
*a = *b;
*b = held;
}
int main(void) {
int left = 1;
int right = 2;
swap(&left, &right);
printf("left %d, right %d\n", left, right);
}
This prints left 2, right 1. The function received two addresses, copied as usual,
and wrote through them.
Now think about a language you know. When a function changes a list you passed it
and the change shows up outside, the language passed an address and followed it for
you. Whether a variable holds a value or the address of one is called value versus
reference semantics, and its home in this series is C#. In C you see
the address, because you wrote the &.
An array is a row with no fence
An array is the simplest idea in memory: values of one type, side by side, with no gaps. Print the addresses and you can see it:
#include <stdio.h>
int main(void) {
int a[4] = {10, 20, 30, 40};
for (int i = 0; i < 4; i++) {
printf("a[%d] = %d at %p\n", i, a[i], (void *)&a[i]);
}
int *p = a;
printf("*(p + 2) = %d\n", *(p + 2));
}
The addresses climb by 4 each time, one int apart. And look at the last line. An
array’s name works as the address of its first element, and adding 2 to a pointer to
an int moves it two ints along, 8 bytes. In fact, a[2] means *(a + 2).
Indexing is arithmetic: start at the beginning, step i elements, read what’s
there. That’s why reading a[1000] takes the same time as reading a[0], in every
language with arrays. The machine doesn’t walk to element 1000; it computes where it
is.
Notice what the row doesn’t have: a length. The four boxes of a don’t come with a
fifth box saying “4”. The compiler knows the length while a is in sight, but hand
the array to a function and the function gets only the address of the first element.
Try it:
#include <stdio.h>
void show(int a[4]) {
printf("inside: %zu bytes\n", sizeof a);
}
int main(void) {
int a[4] = {10, 20, 30, 40};
printf("outside: %zu bytes\n", sizeof a);
show(a);
}
The compiler stops you: 'sizeof' on array function parameter 'a' will return size of 'int *'. Inside show, a is a pointer, 8 bytes on a 64-bit machine, however
long the array was. So C functions that take an array nearly always take its length
as a second argument. Every language that “knows” its array’s length is keeping that
number next to the row for you.
Text is the same story. A C string is an array of bytes with a zero byte at the end to mark where it stops. To find its length, you walk until you hit the zero.
A struct is fields side by side
A struct works like an array whose boxes can be different sizes. Its fields sit in
memory in the order you wrote them, one after another. There’s one wrinkle: the
machine reads an int fastest when its address is a multiple of 4, so the compiler
adds a few unused bytes, called padding, to line things up:
#include <stdio.h>
struct Loose {
char tag;
int count;
char flag;
};
struct Tight {
int count;
char tag;
char flag;
};
int main(void) {
printf("loose: %zu bytes\n", sizeof(struct Loose));
printf("tight: %zu bytes\n", sizeof(struct Tight));
}
A char is one byte. Both structs hold one int and two chars, 6 bytes of data,
but on a typical machine Loose takes 12 and Tight takes 8. In Loose, three
bytes of padding follow tag so that count lines up, and three more follow flag
so that the next Loose in an array lines up too. When you have a million of
something, the order of its fields starts to matter.
Two places to live
Your program’s memory isn’t one undivided row. Two regions matter for everything you write.
The stack is where a function’s local variables live. When a function is called, it gets a fresh stretch of the stack for its variables; when it returns, that stretch is handed to the next call. It’s fast and automatic, and it has one rule you can’t break: a local variable lives only as long as its function call. So this is a mistake:
#include <stdio.h>
int *make_number(void) {
int n = 42;
return &n;
}
int main(void) {
int *p = make_number();
printf("%d\n", *p);
}
make_number returns the address of n, but by the time anyone follows that
address, n is gone and its boxes belong to someone else. A pointer like that,
pointing at memory that’s no longer yours, is called dangling. GCC spots this one
and refuses: function returns address of local variable.
The heap is for values that need to outlive the function that made them. You ask
for a block of bytes with malloc (“memory allocate”), and it’s yours until you
hand it back with free:
#include <stdio.h>
#include <stdlib.h>
int *make_number(void) {
int *n = malloc(sizeof *n);
if (n == NULL) {
exit(1);
}
*n = 42;
return n;
}
int main(void) {
int *p = make_number();
printf("%d\n", *p);
free(p);
}
malloc takes a number of bytes and returns the address of a fresh block, or NULL
if it couldn’t find one. sizeof *n asks “how big is the thing n points at?”,
which keeps the size right if you later change the type. And free(p) gives the
block back.
Now the question every language since has had to answer: who calls free? Here it’s
main, the last one using the number. In a bigger program, the block might be
handed from function to function, stored in a struct, shared by two parts of the
program. Exactly one of them must free it, after everyone is done with it. Free it
too early and someone is left holding a dangling pointer. Free it twice and you
corrupt the heap’s own bookkeeping. Never free it and you have a leak: memory your
program holds and can no longer use.
The question “which part of the program is responsible for this block?” is called ownership. C has no answer for it except the one you keep in your head. Other languages picked answers. Java, Python, JavaScript and C# run a garbage collector, a part of the runtime that finds blocks nobody can reach any more and frees them for you. C++ makes ownership a convention: an object frees its memory when it goes out of scope. Rust makes ownership a rule the compiler checks before your program runs.
Rows and chains
Almost every data structure you’ve used is built from two shapes, and you’ve now seen the raw material for both.
The first shape is a row: one block, values side by side, like an array. Finding
element i is arithmetic, but the size is fixed when you ask for the block. So how
does a list in Python, or an array in lux, grow when you add to it?
It asks for more room than it needs and remembers two numbers: the length, how
many values are in use, and the capacity, how many fit. Adding a value usually
just fills the next spare box. When the spares run out, it asks for a bigger block,
often twice as big, copies everything over, and frees the old one. Copying is slow,
but because the block doubles, it happens rarely, and on average each add stays
cheap. That’s a growable array, and it’s what you’ll build in the project.
Python’s list, Java’s ArrayList, Rust’s Vec and Go’s slices all work this way.
The second shape is a chain: many small blocks, each holding a value and the address of the next. That’s a linked list:
#include <stdio.h>
#include <stdlib.h>
typedef struct Node {
int value;
struct Node *next;
} Node;
Node *push_front(Node *head, int value) {
Node *node = malloc(sizeof *node);
if (node == NULL) {
exit(1);
}
node->value = value;
node->next = head;
return node;
}
int main(void) {
Node *list = NULL;
for (int i = 1; i <= 3; i++) {
list = push_front(list, i * 10);
}
for (Node *n = list; n != NULL; n = n->next) {
printf("%d at %p\n", n->value, (void *)n);
}
while (list != NULL) {
Node *next = list->next;
free(list);
list = next;
}
}
Two small new pieces of C here. typedef gives the struct the short name Node.
And node->value means “follow the pointer node, then take the field value”;
it’s shorthand for (*node).value.
Each node was its own malloc, so the nodes sit wherever the heap had room, not
side by side. Adding at the front is cheap: one small block, no copying, however
long the list is. Finding the 1000th value is not, because there’s no arithmetic
that gets you there. You follow 999 addresses. And look at the cleanup loop at the
end. It saves next before freeing the node, because after free(list), reading
list->next would be reading memory that’s no longer yours.
Trees are chains that branch. Many hash tables are a row of chains. Once you can see these two shapes, you can guess the costs of most of what a standard library gives you before you read its documentation.
Where C stops looking after you
Most languages you know make a promise: if you read past the end of an array, or use something that’s gone, the program stops with an error. C gives up that promise. When you break one of its memory rules, the result is undefined behavior: the language standard says nothing at all about what happens. Often the program reads whatever bytes happen to be there and carries on, wrong and quiet.
Here’s a use of a freed block, hidden inside a function where the compiler can’t see it:
#include <stdio.h>
#include <stdlib.h>
void finish(int *scores) {
free(scores);
}
int main(void) {
int *scores = malloc(3 * sizeof *scores);
if (scores == NULL) {
return 1;
}
scores[0] = 90;
finish(scores);
printf("%d\n", scores[0]);
}
Built without the sanitizers, this ran and printed 1584348641 when I tried it. Not
90, not an error, just a number that happened to be in those boxes. Built with the
usual command, it stops at once, with a report that starts ERROR: AddressSanitizer: heap-use-after-free and names the line that read the freed block,
the line that freed it, and the line that allocated it in the first place. Change i < 4 to i <= 4 in the array example and you’ll get its sibling,
stack-buffer-overflow.
That’s why the sanitizers are in the build command from the first program: they put back the checks C took out.
Beware of ignoring warnings. In most languages a warning is advice. In C it’s
often the only notice you’ll get that your program has undefined behavior in it, and
the program will still compile and may still seem to work, until it doesn’t. Keep
-Wall -Wextra -Werror on, always, and when a warning appears, fix the cause. Don’t
add a cast or a pragma to make it go quiet: a silenced warning is the same bug, now
invisible. Every one you read teaches you a rule of the row you didn’t know yet.
Build a growable array
The project is the row that grows. It’s in projects/c/vec.c. “Vec”, short for
vector, is a common name for a growable array. Here’s the heart of it:
typedef struct {
int *data;
size_t length;
size_t capacity;
} Vec;
void vec_push(Vec *v, int value) {
if (v->length == v->capacity) {
size_t bigger = v->capacity == 0 ? 4 : v->capacity * 2;
int *moved = realloc(v->data, bigger * sizeof *moved);
if (moved == NULL) {
fprintf(stderr, "out of memory\n");
exit(1);
}
printf("grew %2zu -> %2zu: block at %p is now at %p\n",
v->capacity, bigger, (void *)v->data, (void *)moved);
v->data = moved;
v->capacity = bigger;
}
v->data[v->length] = value;
v->length++;
}
A Vec is three things: the address of a block on the heap, the length, and the
capacity. When the block is full, vec_push calls realloc (“reallocate”), which
does the grow-and-copy in one step: it finds a block of the new size, copies the old
contents in, frees the old block, and returns the new address. Sometimes it can
stretch the old block in place, and then the address doesn’t change. Either way, the
old address may no longer be valid, which is why v->data is replaced straight
away.
The file also has vec_get, which checks the index against the length before
reading (the fence that plain C arrays lack), and vec_free, which hands the block
back. Its main pushes the squares of 1 to 20 and adds them up. Build and run it
from the projects/c folder with the same command you’ve used all along:
gcc -std=c23 -Wall -Wextra -Werror -fsanitize=address,undefined -g -o vec vec.c && ./vec
grew 0 -> 4: block at (nil) is now at 0x502000000010
grew 4 -> 8: block at 0x502000000010 is now at 0x503000000040
grew 8 -> 16: block at 0x503000000040 is now at 0x506000000020
grew 16 -> 32: block at 0x506000000020 is now at 0x50c000000040
20 numbers in room for 32, total 2870
the 10th is 100
(nil) is how printf shows NULL on Linux: the first push starts from no block
at all. Twenty pushes, four trips to realloc. Change the 20 in main to 1,000 and
it takes only nine. That’s doubling at work.
Look at the addresses, too. With the sanitizer on, every grow moved the block when I
ran it: the sanitizer holds freed memory back so that stale pointers are easy to
catch. Build without -fsanitize=address,undefined and you’ll probably see some
grows stay put. So a pointer into a Vec can survive one push and dangle after the
next. The second “Try this next” item at the end of the file walks you into that
bug.
What I left out
I skipped the preprocessor (the #include lines and their
relatives), header files and programs split across many files, const, unions,
function pointers, and nearly all of C’s standard library. I didn’t cover build
tools such as make, or the long list of things that count as undefined behavior.
None of them change the picture of the row, and each is easy to pick up once you
have it.
cppreference’s C reference is the place to look things up: every function, every operator, and which version of C added it. Modern C by Jens Gustedt is a whole book on C as it’s written today, updated for C23, and free to read online. Beej’s Guide to C Programming is friendlier, and also free. And GCC’s page on sanitizers lists the other checkers it can build into your program.
Ask the machine
The manual for every C library function is already on your disk. Run:
man 3 malloc
Bring it one question: what does realloc do if it can’t find a bigger block, and
what happens to your old block then? The answer is why the project stores the result
in moved before touching v->data.
Then ask the compiler what your code turned into. Put this in third.c:
int third(int *a) {
return a[2];
}
and run gcc -S -O1 -o - third.c. That prints the machine instructions GCC wrote
for you. Somewhere in there is a[2]. Can you find it, and does it look like “start
at the address, step two ints along”?
Related
- C++ takes the ownership question C leaves open and answers it by convention, with objects that free their own memory.
- Rust answers it with a compiler that checks every rule, and it’s the home of
Option. - C# teaches value and reference semantics, the copy-or-address question from the swap example.
- Debugging is about finding out what a running program is actually doing, the next step once a sanitizer has told you where it went wrong.
Tested with GCC 14.2, November 2026.
The Programming Shortcut: C++
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about ownership and resource lifetime, by convention.
Many languages wearing one name
C++ has a reputation, and it earned it. It is enormous. It contains all of C, a system of classes, a second language for writing code that writes code, a standard library the size of a small city, and forty-odd years of features added on top of each other, with very few ever taken away.
Nobody uses all of it. Not the people who write the compilers, not the committee that designs it. Every team that writes C++ picks a dialect, a sensible subset they agree to live in, and ignores the rest. You get to do the same, starting today.
So this article picks for you. It skips the city and visits one building, the idea C++ gave the rest of programming: a resource belongs to an object, and when the object’s life ends, the resource goes back. Memory, open files, network connections, locks: in the C++ most people write today, almost none of them are ever released by hand. They are released by a closing brace.
Bjarne Stroustrup started the work that became C++ in 1979. He wanted the speed and control of C for programs too big to keep in your head, and the problem of remembering to clean up was one of the first he solved. It is also the part of C++ that will still be useful to you if you never write another line of it, because once you see it here, you will spot it in every language you use.
What you already have
Most of what you know carries over without a fuss:
| What you know | lux | C++ |
|---|---|---|
| a record | struct Point { x: int, y: int } | struct Point { int x; int y; }; |
| a growable array | [1, 2, 3] | std::vector<int>{1, 2, 3} |
| text | string | std::string |
| a value that might be missing | Option | std::optional (and * reads it without checking) |
| an error you expect | Result | std::expected (C++23), or an exception |
| printing a line | print(...) | std::println(...) (C++23) |
| cleanup when you’re done | nothing to clean: readFile closes the file for you | a destructor |
Variables, conditionals, loops, functions and recursion look the way they look in C or Java, braces and semicolons included. You know them. The last row is the one that’s new, and it’s the rest of this article.
Edit, compile, run
C++ is compiled: a program called a compiler reads your whole source file and
turns it into a machine-code program you then run. This article uses one
compiler, g++, from the GNU Compiler Collection (GCC). The steps are shown on
Linux. On Debian or Ubuntu, one command installs it:
sudo apt install g++
For macOS, Windows and other compilers, see isocpp.org/get-started.
Make a file called hello.cpp:
#include <print>
int main() {
std::println("Hello from C++");
}
Then compile it and run it with one line:
g++ -std=c++23 -Wall -Wextra -Werror -fsanitize=address,undefined -o hello hello.cpp && ./hello
That’s a long line, so here’s what it says. -std=c++23 asks for the 2023 edition of
the language. -Wall -Wextra turn on the compiler’s warnings, and -Werror makes
every warning stop the build, so you can’t scroll past one. -fsanitize=... adds
sanitizers: extra checks compiled into your program that watch it run and stop it
loudly when it touches memory it shouldn’t. They’ll matter later. -o hello names
the program, and && ./hello runs it if the build worked.
After this, every change is three keystrokes: edit the file, press the up arrow, press Enter. Keep this terminal open; every example below runs the same way.
Things you borrow from the machine
Start with a word. A resource is anything your program borrows from the operating system and has to give back. Memory is one. An open file is another: the system keeps a little record for every file a program has open, and it only has so many. A network connection, a lock that keeps two threads out of each other’s way, a window on the screen: all resources.
Every resource has a lifetime, the stretch of time between getting it and giving it back. Get it, use it, return it. The rule is simple. Following it is not, because programs don’t run in a straight line. Here’s the shape, in C++ that looks a lot like C:
bool save(const char* path, int score) {
FILE* f = std::fopen(path, "w");
if (!f) return false;
if (score < 0) return false; // oops: f is never closed
std::fprintf(f, "%d\n", score);
std::fclose(f);
return true;
}
One fopen, one fclose, and already a path that leaks. Every return is an exit,
and every exit has to remember. In C, remembering is your job; the
C article is about living with that. Add a few more resources and a few
more exits and you get code where more lines are about cleaning up than about
doing anything.
You’ve probably met a fix for this already. Python has with. Java has
try-with-resources, C# has using, Go has defer. Each one is a way of saying
“when this block ends, however it ends, do this.” If your first language was lux,
you met the problem from the other side: readFile opens, reads and closes in one
call, so you never held a file long enough to forget it.
C++ answers it differently. It doesn’t add a cleanup statement. It ties the resource to an object, and gives every object an ending.
The closing brace does work
A class in C++ is a type with fields and functions attached. (A struct is the
same thing, except that its fields are visible from outside by default.) Two of those
functions are special. The constructor has the class’s name and runs when an
object is made. The destructor has the class’s name with a ~ in front, and it
runs, automatically, when the object’s lifetime ends.
For an ordinary local variable, its lifetime ends at the closing brace of the block it was declared in. You never call a destructor. The brace calls it for you.
#include <print>
#include <string>
class Noisy {
public:
Noisy(std::string name) : name(name) { std::println("hello, {}", name); }
~Noisy() { std::println("goodbye, {}", name); }
private:
std::string name;
};
int main() {
Noisy outer("outer");
{
Noisy first("first");
Noisy second("second");
std::println("inside the block");
}
std::println("after the block");
}
It prints:
hello, outer
hello, first
hello, second
inside the block
goodbye, second
goodbye, first
after the block
goodbye, outer
Look at the order. Objects are destroyed in reverse: last made, first gone. That
isn’t a quirk. If second was built using first, then second has to go while
first is still there, the way you’d take down a tower of blocks from the top.
(The : name(name) bit is how a constructor fills in a field before its body runs.
It does what this.name = name does in Java.)
Now try the exits that broke save. An early return and an exception, which is
C++’s way of stopping a function partway and jumping out to whoever is willing to
handle the problem (the Java article is the place to learn exceptions
properly):
#include <print>
#include <stdexcept>
struct Guard {
const char* name;
~Guard() { std::println("cleaned up after {}", name); }
};
void leave_early() {
Guard g{"leave_early"};
std::println("returning early");
return;
std::println("never printed");
}
void blow_up() {
Guard g{"blow_up"};
throw std::runtime_error("something broke");
}
int main() {
leave_early();
try {
blow_up();
} catch (const std::exception& e) {
std::println("caught: {}", e.what());
}
}
returning early
cleaned up after leave_early
cleaned up after blow_up
caught: something broke
Both exits ran the destructor. The exception didn’t even reach the catch before
blow_up’s guard cleaned up, because leaving a function by an exception still
ends the lives of everything inside it. No matter which way out a block takes,
its objects are destroyed on the way.
(The & in catch (const std::exception& e) means the handler looks at the
exception itself rather than a copy; references come up again below.)
The pattern has a name with a famous handicap: RAII, for Resource Acquisition Is Initialization. Read it as two halves of a promise. The constructor gets the resource. The destructor gives it back. Since the language guarantees the destructor runs, the resource can’t outlive the object that holds it. (Some people call it scope-bound resource management, which says more and is said less.)
Here it is holding something real, a C file handle:
#include <cstdio>
#include <print>
class File {
public:
File(const char* path) : f(std::fopen(path, "w")) {}
~File() {
if (f) std::fclose(f);
std::println("closed");
}
void write(const char* text) { std::fputs(text, f); }
private:
std::FILE* f;
};
bool save(const char* path, int score) {
File out(path);
if (score < 0) return false;
out.write("a good score\n");
return true;
}
int main() {
save("score.txt", -1);
save("score.txt", 10);
}
Same function, same early return, and now there’s nothing to forget. The file closes on both paths, because the object that holds it ends on both paths.
One owner
RAII raises a question it can’t answer on its own. If an object gives its resource back when it dies, what happens when there are two of them?
Picture a copy of out. Two File objects, each holding the same FILE*, each
with a destructor that closes it. The first destructor closes the file. The second
closes it again. Closing a file twice is a bug in C, and in C++ it’s the same bug
with a nicer coat on. (What a copy actually contains, the value itself or just a way
to reach it, is the subject of the C# article.)
The answer is a rule you’ve probably followed without naming it, the one about library books. Lots of people can read a book, but exactly one person checked it out, and that person brings it back. That person is the owner. Ownership means: for every resource, there is one object responsible for releasing it.
C++ lets you write that rule into a class. You can forbid copies outright:
#include <cstdio>
class File {
public:
File(const char* path) : f(std::fopen(path, "w")) {}
~File() { if (f) std::fclose(f); }
File(const File&) = delete;
File& operator=(const File&) = delete;
private:
std::FILE* f;
};
int main() {
File a("a.txt");
File b = a;
}
File(const File&) is the copy constructor, the function that would make a copy.
(The & means it receives the original itself rather than a copy of it; more on
that below.) = delete removes it. Now the compiler refuses:
error: use of deleted function ‘File::File(const File&)’
That’s the first time in this article the compiler has helped, and it’s a fair deal: one line in the class, and nobody can make the double-close mistake with it.
Handing it over
A thing that can never be copied is a bit stuck, though. You want to make a file in
one function and hand it to another, or keep several in a std::vector. Library
books get passed between friends, too; the point is that only one person has the
book at a time.
That’s a move. Moving an object hands its resource to a new object. For a class written like this
one, or for unique_ptr, the old object is left empty, so its destructor has nothing
to give back. (Other standard types promise less: a moved-from object is safe to
destroy or assign to, and nothing more.) C++
writes it with std::move:
#include <memory>
#include <print>
#include <utility>
int main() {
std::unique_ptr<int> mine = std::make_unique<int>(42);
std::println("mine holds {}", *mine);
std::unique_ptr<int> yours = std::move(mine);
std::println("yours holds {}", *yours);
std::println("mine is empty: {}", mine == nullptr);
}
std::unique_ptr is the standard library’s ready-made owner for memory. A
pointer is a value that holds a memory address (the C article has the full
story), and a unique_ptr is a pointer with a destructor that frees what it points
to. It can’t be copied. It can be moved. std::make_unique<int>(42) asks for room
for one int, puts 42 in it, and gives you the owner.
The name std::move is a little misleading, so here’s what it does: nothing,
by itself. It’s a label that says “I’m finished with this; whoever receives it may
take what’s inside.” The receiving object does the taking.
That’s enough to say what a function wants just by looking at its parameters. The types tell you who owns what:
void keep(std::unique_ptr<Photo> photo); // takes ownership: you hand it over
void show(const Photo& photo); // borrows: just looking
std::unique_ptr<Photo> load(const char* path); // gives ownership to you
The & makes a reference, a second name for an object that lives somewhere else.
A reference owns nothing; when it goes away, nothing is released. Passing one is
called borrowing: you get to use the thing, and its owner still has to give it
back.
And for the rare thing that really does have several owners, there’s
std::shared_ptr. It keeps a count of how many owners exist, and the last one to
leave turns off the lights:
#include <memory>
#include <print>
int main() {
auto first = std::make_shared<int>(7);
std::println("owners: {}", first.use_count());
{
auto second = first;
std::println("owners: {}", first.use_count());
}
std::println("owners: {}", first.use_count());
}
That prints 1, then 2, then 1. When first goes away too, the count hits zero and
the memory goes back. Copying a shared_ptr is allowed, because copying is how you
add an owner.
Put these together and something quiet happens. Most classes in modern C++ don’t
need a destructor at all. A class that holds a std::string, a std::vector and a
std::unique_ptr already cleans up after itself, because each of its fields is an
owner, and the fields’ destructors run when the class’s does. People call this the
rule of zero: write no cleanup code, and build from parts that already know how.
You’ll write a destructor yourself only at the bottom of the tower, where something
like a FILE* from C first comes in.
Nobody is checking
Here’s where C++ parts company with some of the languages you may know. Ownership in C++ is a convention: a set of habits the language makes easy and the standard library follows. The compiler enforces some of it, like the deleted copy. Most of it, it doesn’t check at all.
Using a unique_ptr after you’ve moved out of it compiles without a murmur:
#include <memory>
#include <print>
#include <utility>
int main() {
auto note = std::make_unique<int>(42);
auto other = std::move(note);
std::println("{}", *note);
}
So does borrowing from something that’s about to move. A std::vector that grows
gets a bigger block of memory and moves its elements there, which leaves every
reference into the old block pointing at memory that has been given back:
#include <print>
#include <string>
#include <vector>
int main() {
std::vector<std::string> names = {"Ada"};
std::string& first = names[0];
names.push_back("Grace");
std::println("{}", first);
}
-Wall -Wextra -Werror said nothing about either one. The sanitizers caught both,
but only while the program ran, and only because the bad line actually ran. That’s
the trade C++ makes: you get the ownership ideas, and you keep the job of following
them. The Rust article shows the other choice, a compiler that checks
every move and every borrow before your program runs, and turns down both of these
programs.
The habit that keeps you safe is short. Never write new or delete; use
std::make_unique and let an owner do it. Don’t use something after you’ve moved
it. Don’t hold a reference into something that might grow, move or die before you’re
done with it.
Beware of trying to learn all of it. C++ has a feature for everything and three ways to do most things, and every corner has a passionate expert. Don’t chase the corners. Pick the small dialect this article used: classes that own things,
std::unique_ptr,std::vector,std::string, references for borrowing, and nothing raw that owns. That dialect is real C++, it’s what good code looks like, and it will carry you a long way. When an old tutorial hands younewanddelete, close it and find a newer one.
A file that tidies up after itself
The project is one file: a class called Scratch that makes a temporary file,
lets you write to it, and deletes it from the disk when its lifetime ends. It’s
built so you can watch, because the file appears in the directory and then
disappears.
Copy projects/cpp/scratch.cpp into a folder of
its own and build it the same way as before:
g++ -std=c++23 -Wall -Wextra -Werror -fsanitize=address,undefined -o scratch scratch.cpp && ./scratch
Here’s the class. It’s the File from earlier, grown up: it refuses copies, it
can be moved, and its destructor closes the file and then removes it.
class Scratch {
public:
explicit Scratch(std::string name) : name_(std::move(name)), file_(std::fopen(name_.c_str(), "w")) {
if (!file_) {
throw std::runtime_error("could not create " + name_);
}
std::println(" [open {}]", name_);
}
~Scratch() {
if (!file_) {
return;
}
std::fclose(file_);
std::filesystem::remove(name_);
std::println(" [remove {}]", name_);
}
Scratch(const Scratch&) = delete;
Scratch& operator=(const Scratch&) = delete;
Scratch(Scratch&& other) noexcept
: name_(std::move(other.name_)), file_(std::exchange(other.file_, nullptr)) {}
Scratch& operator=(Scratch&&) = delete;
// ...
The new piece is Scratch(Scratch&& other), the move constructor. The && marks
an object someone has said they’re finished with. The move constructor takes that
object’s name and file handle, and std::exchange leaves nullptr (no file) in
its place. That’s why the destructor starts by checking file_: an emptied object
has nothing to give back. The noexcept promises that the move can’t throw, which
lets a growing std::vector move its elements instead of trying to copy them. The
two operator= lines turn off assignment, by copy and by move, to keep the class
small.
If fopen fails, the constructor throws. An object whose constructor didn’t
finish gets no destructor call, and that’s right: it has no file, so there’s
nothing to clean up.
The rest of the file is a main that runs four little scenes. When you run it
you’ll see:
1. A block:
[open notes.tmp]
notes.tmp exists? true
[remove notes.tmp]
notes.tmp exists? false
2. An exception:
[open work.tmp]
work.tmp exists? true
[remove work.tmp]
caught: step two failed
work.tmp exists? false
3. A move:
[open draft.tmp]
[open log.tmp]
draft.tmp exists? true
log.tmp exists? true
4. The end of main:
[remove draft.tmp]
[remove log.tmp]
Read it scene by scene. In the first, the file lives as long as the block, and no longer.
In the second, a function throws halfway through its work, and the file is gone
before the catch even prints. In the third, a function makes a file and returns
it, and main moves another into a std::vector. Neither is removed when the
function or the variable that made it ends, because neither was the owner by then.
They go at the very end, when the vector does, once each.
Count the [remove] lines: four files opened, four removed, and no line in main
that removes anything.
What I left out
Almost everything. Templates, inheritance and virtual functions,
operator overloading, the many kinds of constructor, const in all its moods,
namespaces, headers and building programs from more than one file, and the long
list of rules about when the compiler writes copy and move functions for you. Also
left out: how && works in detail, which deserves a sitting of its own. Every one
of those is real, and you can write good C++ for a while without any of them.
When you want more, go to the people who make the language. A Tour of C++ is Stroustrup’s own short overview. cppreference.com is the reference everyone uses, and its RAII page is a good next read. The C++ Core Guidelines have a whole section of rules on resource management, written by Stroustrup and Herb Sutter, and the first rule in it is the idea from this article.
Look at what the brace costs
Is all this cleanup free? Ask the compiler. Save these two functions as
owners.cpp. They do the same work, one by hand and one with an owner:
#include <memory>
void use(int* p);
void by_hand() {
int* p = new int(42);
use(p);
delete p;
}
void by_owner() {
auto p = std::make_unique<int>(42);
use(p.get());
}
Then ask g++ to stop before making a program and show you the machine
instructions it would have used, with full optimization:
g++ -std=c++23 -O2 -S owners.cpp
Open owners.s. Under _Z7by_handv and _Z8by_ownerv (the compiler’s spelled-out
names for your two functions), compare the instructions from the first call to
the jmp at the end. Then look for the one thing by_owner has that by_hand
doesn’t, near _Unwind_Resume, and bring this question: if use throws an
exception, where does by_hand free its memory?
Related
- C: memory, pointers and the data structures built on them; what the machine does when nobody owns anything.
- Rust: ownership and borrowing again, checked by the compiler before the program runs.
- Java: exceptions, the other way out of a function.
- C#: value and reference semantics, or what a copy contains.
Tested with G++ 14.2 (-std=c++23), November 2026.
The Programming Shortcut: Python
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about standing on libraries, and duck typing.
Most of your program is already written
Python is a language for getting things done, and it gets them done by letting you borrow.
When you write a Python program that renames a folder of photos, or totals a spreadsheet, or checks which of your files are copies of each other, you write perhaps thirty lines. Underneath those thirty lines sit many thousands more that somebody else wrote, tested and documented, and that came with Python when you installed it. Python’s own people call this “batteries included.” The standard library, the collection of ready-made code that ships with the language, is enormous, and it’s the reason a beginner’s Python script can do things that would take days in a language without one.
The new idea in this article is the skill that goes with it: standing on libraries. Using code you didn’t write, written by people who never met you, for problems they had never seen. And the trick that makes it work in Python is called duck typing, which sounds silly and is one of the most useful ideas in programming.
You won’t learn much Python syntax here. You’ll learn how to plug your code into somebody else’s, and why it fits.
What you already know, in Python
Python spells the familiar things like this:
| What you know | lux | Python |
|---|---|---|
| a function | func area(w: int) -> int { … } | def area(w): |
| a block of code | braces { … } | indentation: the lines indented under the : |
| a record | struct | a class marked @dataclass |
| a value that might be missing | Option | None |
| errors you expect | Result | exceptions |
| a lookup table from keys to values | none: you build one | dict: {"cat": 2, "mat": 1} |
| code someone else wrote | none beyond the built-ins | import |
| when types are checked | before running, every branch | never by the language |
Variables, conditionals, loops, lists and recursion all work the way you expect, so this article will use them without comment. Indentation is the one surprise: Python has no braces, and the indentation is the block. Your editor will help.
Two rows deserve a pointer. Exceptions are errors that jump out of a function instead of being returned from it, and Java is where this series explains them. “When types are checked” is the question the introduction asks of every language, and Python’s answer turns out to matter a lot below.
Edit, then run
Python needs one tool: the python3 command, plus any text editor you like. If
you don’t have Python yet, the installers are at
python.org/downloads. Most Linux systems
already have it; type python3 --version in a terminal to find out.
The commands in this article are written for a macOS or Linux terminal. On
Windows, the Python install manager gives you a py command; type py wherever
this article says python3 (the details are in
Using Python on Windows).
Make a file called hello.py:
name = "library"
print("Hello,", name)
Then run it:
python3 hello.py
It prints Hello, library. From here on: edit the file, save it, run it
again. There’s no compile step to wait for. Python reads your file and runs it,
top to bottom.
Keep that file open. You’re about to borrow something.
Someone already wrote that
Suppose you want to know which words turn up most in a piece of text. You know how to do this. Make a lookup table, walk the words, add one each time:
text = "the cat sat on the mat and the cat slept"
counts = {}
for word in text.split():
counts[word] = counts.get(word, 0) + 1
print(counts)
That works, and you could take it further: sort the table by count, pick the top two. Ten minutes of careful work, maybe less.
Or you could notice that counting things is a problem every programmer has had,
and that somebody has solved it already. Replace the contents of hello.py with
this and run it:
from collections import Counter
text = "the cat sat on the mat and the cat slept"
print(Counter(text.split()).most_common(2))
It prints [('the', 3), ('cat', 2)]: the two most common words, with their
counts, most common first. One line did what your loop did, plus the sorting you
hadn’t written yet.
That first line is the new part. collections is a module: a file of Python
code, usually written by somebody else, that your program can use. Counter is
one of the things defined in it. from collections import Counter means “go and
find the collections module, and let me use its Counter here.”
This is the habit this article is about, in miniature. Before you write the loop, ask: has someone already written this? In Python, for ordinary problems (dates, files, text, numbers, the web), the answer is usually yes, and it’s usually already on your disk.
A module is just a file
import can feel like magic, so take the magic away. Ask a module where it lives:
import random
print(random.__file__)
On a Linux machine with Python 3.13 that prints something like
/usr/lib/python3.13/random.py. It’s a plain text file, in the same language
you’re writing, sitting on your own disk. You could open it in your editor right
now and read how Python picks random numbers. (Look, but don’t change it: every
Python program on your machine uses that file.)
When you write import random, Python finds that file, runs it once, and gives
you one name, random, that holds everything the file defined. You reach inside
with a dot: random.choice(["heads", "tails"]). That name is a namespace, a
container that keeps the module’s names apart from yours, so its choice doesn’t
collide with any choice you might write yourself.
And because a module is just a file, you can make one. Put this in a file called
greet.py:
def hello(name):
return "Hello, " + name + "!"
Then, in another file in the same folder:
import greet
print(greet.hello("Ada"))
Run the second file and it prints Hello, Ada!. Nothing about greet.py is
special. The modules that ship with Python are files like it, only written by
people with more time and more tests.
Reading the label
Using someone else’s code well comes down to one skill: reading the label. You
don’t need to know how Counter works inside. You need to know what it wants from
you and what it gives back.
Python keeps that label with the code. Every module, class and function carries
its own documentation, and the help function prints it. Add
help(Counter.most_common) to a script, or type it into Python’s interactive
prompt (more on that at the end), and it tells you what most_common takes and
returns. The same text, with examples, is in the
library reference, which is worth
skimming once just to see how much is in there.
Now look closely at what Counter wants, because this is where Python gets
interesting.
If it quacks like a duck
Counter(text.split()) gave Counter a list of words. What else will it take?
from collections import Counter
print(Counter("banana"))
print(Counter(["red", "blue", "red"]))
print(Counter(range(3)))
A string, and it counts letters. A list, and it counts the items. A range, and
it counts numbers. Counter was written once, by someone who had never seen your
program, and it works on all three.
How? Counter never asks what type of thing you gave it. It only does one thing
with it: it loops over it, taking items one at a time. Anything that can be looped
over works. Python’s word for “something you can loop over” is an iterable, and
the documentation for Counter says it counts elements “from an iterable.” It
doesn’t say “from a list.”
That’s duck typing. The name comes from an old saying: if it looks like a duck and quacks like a duck, it’s a duck. Python’s version is more practical: if it can do what I’m about to ask of it, I don’t care what it is. A function written in this style doesn’t check the type of what it’s given. It calls the methods it needs and trusts them to be there.
In lux, every function names its parameter’s type, text: string, and lux holds
you to it before the program runs. A Python library makes a looser promise: give
me anything that can do this, and I’ll work.
Plugging your own code in
Duck typing works in both directions, and the second direction is the powerful one. It isn’t only that a library accepts many of Python’s types. It accepts yours too, as long as yours can quack.
Here’s a library function you have used since your first program. Run
help(print) and part of what it says is:
file
a file-like object (stream); defaults to the current sys.stdout.
print writes to the screen by default, but you can hand it somewhere else to
write. A file-like object is anything that behaves like an open file. And what
does print actually do with that object? It calls one method on it: write,
with the text to write. That’s the duck. Anything with a write method quacks.
So make one. A class is a way to define your own kind of object along with the
functions that belong to it, which are called methods. This one has a single
method, write, that shouts whatever it’s given:
import sys
import json
class Shouter:
def write(self, text):
sys.stdout.write(text.upper())
loud = Shouter()
print("hello from print", file=loud)
json.dump({"name": "Ada", "langs": ["lux", "python"]}, loud)
print()
(self is how a method refers to the object it belongs to. You can ignore it
here. sys.stdout is the screen, as a file-like object.)
Run it:
HELLO FROM PRINT
{"NAME": "ADA", "LANGS": ["LUX", "PYTHON"]}
Two libraries that know nothing about Shouter just used it. print sent it a
line of text. json.dump, which turns Python data into JSON (JavaScript Object
Notation, the text format most of the web uses to swap data), sent it a JSON
document in pieces. Neither checked what loud was. Each called write, and
write was there.
The documentation for json.dump describes what it wants as “a .write()-supporting
file-like object.” Read that phrase again. It doesn’t name a type at all. It names
a behavior. That phrase, or one like it, turns up all over Python’s
documentation.
This is why standing on libraries in Python feels so easy. Library authors write
against behaviors, not types, so the pieces fit together without anyone planning
for it. A function that writes to the screen can write to a file, or to memory, or
to a network connection, or to something you invented five minutes ago, because
all of them answer to write.
Other languages reach the same goal by writing the agreement down. A Swift protocol is a named list of methods a type promises to have, and the compiler checks the promise before anything runs; Swift is where this series teaches it. Python makes the same arrangement with nothing written down at all.
When the duck doesn’t quack
So what happens when you hand a library something that can’t do what it asks?
import json
class Mute:
pass
json.dump({"name": "Ada"}, Mute())
Mute has no methods at all. Save it as mute.py, run it, and Python stops:
Traceback (most recent call last):
File "/home/you/mute.py", line 6, in <module>
json.dump({"name": "Ada"}, Mute())
~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^
File "/usr/lib/python3.13/json/__init__.py", line 180, in dump
fp.write(chunk)
^^^^^^^^
AttributeError: 'Mute' object has no attribute 'write'
That report is a traceback: the chain of function calls Python was in the middle
of when it stopped, oldest at the top, newest at the bottom. Read it from the
bottom up. The last line is what went wrong: something tried to call write on a
Mute, and there was no write. The line above it says where: inside the json
library’s own file, at the moment it tried to quack your duck. One step further
up is your line, the call that handed the library the wrong thing.
Notice when this happened. Python didn’t look at Mute when you defined it, or
when you passed it to json.dump. It found out at the last possible moment, when
the library reached for a method that wasn’t there. If that call had been inside an
if that didn’t run, you wouldn’t have heard about it. That’s Python’s answer to
the introduction’s question: the language itself never checks types ahead of time.
It just tries.
What you give up
Duck typing is generous, and the price of generosity is that nobody writes the agreement down.
In a language that checks types before running, the agreement between your code and a library is part of the program. If you hand a function the wrong thing, you hear about it before anything runs, at the line where you made the mistake. In Python the agreement lives in documentation and in the library’s habits. You learn it by reading the label, and if you read it wrong you learn it from a traceback, at runtime, in a file you didn’t write.
That has two practical consequences. First, test the branches you care about, because nothing else will look at them. Second, when a traceback ends inside a library, don’t assume the library is broken. Walk up the traceback until you reach a line of yours: that’s almost always where the mistake is.
If you want the agreement written down, Python lets you add it. Type hints, like
def hello(name: str) -> str, record what a function expects, and a separate
checker such as mypy reads them before you run anything.
The language itself ignores them. That idea, static checking as a tool you choose,
gets its own article: TypeScript.
There’s one more thing you give up, and it applies to every language with libraries: when you import someone’s code, it runs on your machine with all of your permissions, and its bugs become your bugs. The standard library is about as trustworthy as code gets. Code from strangers on the internet deserves a little more reading before you stand on it.
Beware of the packaging-tool debate. The standard library goes a long way, but
eventually you’ll want something it doesn’t have, and you’ll find out that the
wider Python world installs third-party code with a crowd of competing tools, each
with fans who will tell you the others are wrong. Pick one and ignore the rest. My
advice is the pair that ships with Python itself: python3 -m venv to make a
virtual environment (a private folder of libraries for one project, so projects
can’t break each other) and pip inside it to install what you need. It isn’t the
fanciest option, and it works everywhere Python does. Many Linux systems now
refuse to let pip install into the system’s own Python at all, which is that
same advice enforced. And before you install anything, check the standard library
first. You’ll be surprised how often the battery was already in the box.
The project: find your duplicate files
Every computer collects duplicates: the photo you downloaded twice, the backup of a backup. Finding them by hand is tedious. Finding them with Python takes about fifty lines, and most of the work is done by four modules you don’t have to write.
Here’s the plan. Two files are duplicates if they have the same contents. Comparing every file with every other file would be slow, so first group files by size (files of different sizes can’t match), and only for sizes shared by two or more files, compute a fingerprint of the contents. A fingerprint here is a hash: a short string computed from a file’s bytes, which changes completely if even one byte changes. Files with the same hash have the same contents.
Make a folder for the project, and in it a file called dupes.py:
import sys
from collections import defaultdict
from hashlib import file_digest
from pathlib import Path
def fingerprint(path):
with path.open("rb") as f:
return file_digest(f, "sha256").hexdigest()
def find_duplicates(folder):
by_size = defaultdict(list)
for path in Path(folder).rglob("*"):
if path.is_file():
by_size[path.stat().st_size].append(path)
by_content = defaultdict(list)
for paths in by_size.values():
if len(paths) > 1:
for path in paths:
by_content[fingerprint(path)].append(path)
groups = [paths for paths in by_content.values() if len(paths) > 1]
return sorted(groups, key=wasted_bytes, reverse=True)
def wasted_bytes(paths):
return paths[0].stat().st_size * (len(paths) - 1)
def report(groups, out):
if not groups:
print("No duplicates found.", file=out)
for paths in groups:
print(f"{len(paths)} copies, {wasted_bytes(paths):,} bytes to reclaim:", file=out)
for path in sorted(paths):
print(" ", path, file=out)
def main():
if len(sys.argv) < 2:
sys.exit("usage: python3 dupes.py FOLDER [REPORT-FILE]")
groups = find_duplicates(sys.argv[1])
if len(sys.argv) > 2:
with open(sys.argv[2], "w") as out:
report(groups, out)
print(f"Wrote {len(groups)} groups to {sys.argv[2]}")
else:
report(groups, sys.stdout)
main()
The full file, with a “Try this next…” list at the end, is in
projects/python/dupes.py.
Read it for what it borrows, because that’s most of it:
pathlib.Path knows about folders and files. rglob("*") walks a folder and
every folder inside it, handing back each path it finds. You didn’t write a
recursive folder walk.
collections.defaultdict(list) is a lookup table that starts every new key with an
empty list, so by_size[size].append(path) works the first time a size turns up.
You didn’t write “if this key isn’t there yet, add it.”
hashlib.file_digest computes the SHA-256 hash (one well-known recipe for
fingerprints) of a file. Its documentation says it wants “a file-like object
opened for reading in binary mode.” That’s a duck again: it doesn’t care what
f is, only that it behaves like a file opened for binary reading.
sys.argv is the list of words typed on the command line, and sys.stdout is the
screen.
sorted is built in, and it’s a duck-typed function you’ve been using all along:
it takes anything iterable and hands back a sorted list. Its key argument names a
function, here wasted_bytes, that says what to sort by.
Two small pieces of Python syntax turn up too. The square brackets in
[paths for paths in ... if len(paths) > 1] build a list from a loop and a
condition in one line; it’s the loop you’d write anyway, folded up. And an f
before a string, as in f"{len(paths)} copies", fills in each {…} with the value
inside it.
And there’s one more duck, the one you wrote. report takes an argument called
out and only ever passes it to print(..., file=out). In main, it gets the
screen when you don’t name a report file, and a real open file when you do. The
report function doesn’t know or care which. It’s the Shouter trick, put to
work.
There’s also a library call disguised as a keyword. with open(...) as out: opens
a file and guarantees it gets closed when the indented block ends, even if
something goes wrong inside.
Run it on a folder that’s likely to have copies in it, such as your downloads:
python3 dupes.py ~/Downloads
You’ll see each group of identical files, the largest wasted space first. Here’s
what it printed for a small test folder called photos:
3 copies, 100,000 bytes to reclaim:
photos/big.bin
photos/big2.bin
photos/old/big-backup.bin
2 copies, 10 bytes to reclaim:
photos/beach.jpg
photos/old/beach-copy.jpg
Your own folder will give different results, of course, and if you’re tidier than most you’ll
see No duplicates found. Copy a file or two into the folder and run it again.
Now name a report file, and the same report function writes there instead:
python3 dupes.py ~/Downloads dupes.txt
The script only reports. It never deletes anything, which is the right first version of any program that looks at your files.
What’s left out, and where to go next
This article skipped most of what Python can do, because the
idea was to learn how to borrow, not what to borrow. It left out classes beyond
the two tiny ones you made, and the dunder methods (“double underscore,” with names
like __len__ and __iter__) that let your own classes quack like Python’s built-in types. It
left out typing.Protocol, Python’s way of writing a duck down so a checker can
hold you to it. It left out packages from outside the standard library, virtual
environments beyond one sentence, and the long, mostly settled story of Python 2.
And it left out the more cautious style of duck typing, where code asks whether
something has a method before calling it.
When you want more, go to the people who make the language. The official Python tutorial is clear and complete, and the library reference is the catalog of everything that came in the box. Its contents page alone will give you ideas for programs to write.
One last thing to try
Type python3 on its own, with no file. You get Python’s REPL (read, evaluate,
print, loop): a prompt where you type one line, Python runs it, and shows you the
result.
At the >>> prompt, type import this. Python prints its own philosophy, The Zen of
Python, in nineteen short lines. Some of it will
make more sense after this article than before.
Then bring it a question. Type import json, then help(json.dump), and find the
words that describe fp. Does it ask for a type, or for a behavior? Now pick any
library function you’re curious about and ask help the same thing: what does
this need from me? Type q to leave the help page and exit() to leave the REPL.
Related
- Swift: protocols, the same agreement as duck typing, written down and checked before running.
- TypeScript: static checking as a tool you choose, the approach Python’s type hints and mypy take.
- Java: exceptions, Python’s way of reporting errors.
Tested with Python 3.13.5, November 2026.
The Programming Shortcut: JavaScript
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about event-driven programming.
You already own a programming environment
Look up from this article for a second. The program you are reading it in is a browser, and every browser ships with a JavaScript engine, a console for talking to it, and a full set of tools for poking at what it’s doing. You didn’t install any of that. Nobody asked you to. It came with the thing you use to read the news.
So JavaScript is already on nearly every computer and phone you’ve ever touched, and it got there by being made for one job: making a web page do something when you touch it. Not crunching numbers. Not reading files. Responding.
That job forces JavaScript to be very good at an idea most programs only meet later, and usually the hard way: code that waits for things to happen. A click. A key. A timer running out. An answer arriving from a server somewhere. That idea is called event-driven programming, and it’s what this article is about. JavaScript is simply the place where you can’t avoid it.
What carries over
You already know variables, decisions, loops, functions and records. JavaScript has all of them, spelled much as you’d guess. Here’s how a few of them line up:
| What you know | lux | JavaScript |
|---|---|---|
| a variable | let (fixed), var (changes) | const (fixed), let (changes) |
| a function | func add(a: int, b: int) -> int | function add(a, b) |
| a record | struct | an object: { dish: "Toast", seconds: 2 } |
| a value that might be missing | Option | null, and also undefined |
| an error you expect | Result | an exception, or a rejected promise (below) |
| when types are checked | before running, every branch | never (why that matters) |
| waiting for a person | input() stops the program | a listener; nothing stops |
That last row is the article. Everything above it you can pick up as you go.
Edit, save, refresh
Your one tool is the browser you already have, plus any text editor. Make a folder,
and in it a file called waiting.html:
<!doctype html>
<title>Waiting</title>
<button>Click me</button>
<script>
console.log("1. The script starts");
const button = document.querySelector("button");
button.addEventListener("click", () => {
console.log("3. Somebody clicked");
});
console.log("2. The script is finished");
</script>
Open the file in your browser. You’ll see a lonely button. To see what the script said, open the browser’s developer tools with F12 (or Cmd+Option+I on a Mac) and pick the Console tab. If your browser does something different, MDN Web Docs, Mozilla’s reference for the web, has the details for each one.
The console says:
1. The script starts
2. The script is finished
Now click the button. A third line appears. Click again, and another.
That’s how you’ll work from here: edit the file, save it, refresh the page, watch the console. Keep the console open from here on. It’s where JavaScript talks back.
A few pieces of that file are new, and each one gets a sentence.
document.querySelector("button") finds the first button on the page.
console.log prints to the console. And () => { ... } is an arrow function: a
function with no name, written right at the spot where it’s needed. It’s an
ordinary function in every other way.
But look at what just happened, because it’s strange. The script ran from top to bottom and finished. It said so: “The script is finished.” And yet the third line printed afterward, as many times as you liked. Something ran your code after your program was over.
Code that waits
Your program ends, and the page keeps going
In most of the programs you’ve written, the program is in charge. It starts at the
top, does its work, maybe stops to ask for input, and ends. If you know lux,
input() is a good picture of this: the whole program halts on that line until
somebody types, and nothing else happens in the meantime.
A web page can’t work like that. It has to scroll, play a video, respond to a dozen buttons and keep a clock ticking, all at once, while the person in front of it does whatever they please. If the page stopped to wait for one thing, every other thing would freeze.
So JavaScript in a browser turns the arrangement around. Your script doesn’t wait for anything. It runs once, at the start, and its job is to set things up: to tell the browser “when this happens, call that.” Then it ends. From then on the browser is in charge, and your code runs only when the browser calls it.
That’s event-driven programming. Three words carry it:
An event is something that happened: a click, a key press, the page finishing loading, a timer running out, data arriving.
A listener (also called a handler) is a function you want called when a particular event happens.
The event loop is the part of the browser that waits for events and calls the matching listeners, one at a time, for as long as the page is open.
Your waiting.html did all three. The script set up one listener and ended. The
event loop kept waiting. Each click was an event, and each time, the loop called
your arrow function.
Handing over a function
The line that made it work is this one:
button.addEventListener("click", () => {
console.log("3. Somebody clicked");
});
addEventListener takes two things: the name of an event, and a function. Not the
result of calling a function, the function itself, handed over like any other
value, for the browser to keep and call later. A function you hand over this way is
called a callback, because someone else will call it back.
If your first language didn’t let you pass functions around as values, this is the one new move in the article. Everything else is built on it. It also explains a classic mistake:
function cheer() {
console.log("Hooray!");
}
button.addEventListener("click", cheer);
button.addEventListener("click", cheer());
The first line hands over cheer, so the browser calls it on each click. The
second line calls cheer right away, while setting up, prints “Hooray!” once,
and hands the browser the result. cheer returns nothing, so that line quietly
sets up no listener at all, and no error tells you so. The parentheses are the difference between “here’s what to do” and “do it now.”
One thing at a time
Here’s where the event loop gets interesting. JavaScript in a page runs on a single thread, meaning one line of your code is running at any moment, never two. The event loop keeps a queue of things that have happened, and it takes them in order. Each listener runs from start to finish before the next one begins. Nothing interrupts it halfway through. This rule has a name, run to completion, and it’s the reason you don’t have to worry about two clicks scrambling the same variable.
You can see the queue with a timer. setTimeout(callback, ms) asks the browser to
call your function after that many milliseconds. What happens if you ask for zero?
<!doctype html>
<title>Zero</title>
<script>
console.log("A: before");
setTimeout(() => console.log("C: the timer"), 0);
console.log("B: after");
</script>
It prints A, B, C. A delay of zero doesn’t mean “now.” It means “as soon as you’re free,” and the browser isn’t free until the current script has run to completion. The timer’s callback waits in the queue like everybody else.
The same rule has a dark side. If one listener takes a long time, everything else waits for it. Try this page:
<!doctype html>
<title>Hog</title>
<button id="hog">Hog the page</button>
<button id="ping">Ping</button>
<script>
document.querySelector("#ping").addEventListener("click", () => {
console.log("ping");
});
document.querySelector("#hog").addEventListener("click", () => {
console.log("hogging for three seconds");
const start = Date.now();
while (Date.now() - start < 3000) {}
console.log("done hogging");
});
</script>
(Date.now() is the current time in milliseconds, so that while loop spins for
three seconds.) Click Hog, then click Ping a few times while it’s busy. Nothing happens. Then the three seconds end, “done hogging”
appears, and all your pings arrive at once. They weren’t lost. They were waiting in
the queue for a loop that was stuck inside your while.
That’s the bargain of event-driven code: every listener should do its bit quickly and hand control back. Which raises an awkward question. What about things that are supposed to take a long time?
Waiting without stopping
Say a listener needs an answer from a server. The answer might take two seconds. You can’t sit in a loop for two seconds, as you just saw. So instead you ask for the answer and say what to do once it arrives: another callback.
That works, and for years it was how everyone did it. But a callback inside a callback inside a callback gets hard to read fast, and errors have nowhere obvious to go. So JavaScript grew a better shape for “later.”
A promise is an object that stands for a value that isn’t here yet. It starts out pending. Later it settles one of two ways: it’s fulfilled with a value, or it’s rejected with an error. Anything slow in a browser hands you a promise right away and settles it when the work is done.
Here’s a tiny promise of your own. wait gives back a promise that is fulfilled
after ms milliseconds:
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
new Promise calls your arrow function with a function, here named resolve, and
you call it when the value is ready. Here the timer calls it for you.
A promise on its own is just a ticket. The good part is how you wait for one.
async and await
Two keywords turn waiting into ordinary-looking code. Mark a function async, and
inside it you may write await in front of a promise. Here’s breakfast:
<!doctype html>
<title>Breakfast</title>
<script>
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function breakfast() {
console.log("toast in");
await wait(1000);
console.log("toast up, butter on");
await wait(500);
console.log("eat");
}
breakfast();
console.log("breakfast() has already returned");
</script>
The console shows:
toast in
breakfast() has already returned
toast up, butter on
eat
Read that order slowly.
breakfast() starts running like any function. It prints “toast in.” Then it hits
await wait(1000). At that moment the function pauses: it sets itself aside,
remembering where it was and every local variable it had, and hands control back to
whoever called it. That’s why “has already returned” prints second. The script
finishes. The event loop is free. Clicks, scrolling and other timers all carry on
as normal.
A second later the promise is fulfilled, and the event loop picks breakfast back
up at the line after the await, as if it had never left. Same function, same
variables, one second later.
So await means “pause this function until the promise settles, and let
everything else carry on.” It doesn’t stop the page, the way the while loop did,
or the program, the way lux’s input() does. It stops one function, politely.
Three more facts make async and await complete.
An async function always returns a promise. Even if it says return 42, the
caller gets a promise that will be fulfilled with 42. That’s how the caller can
await it in turn. Forget the await, and you get the promise itself, not the
value:
<!doctype html>
<title>Forgot</title>
<script>
async function lookUp() {
return 42;
}
async function main() {
const forgot = lookUp();
const remembered = await lookUp();
console.log("The answer is " + forgot);
console.log("The answer is " + remembered);
}
main();
</script>
The first line prints The answer is [object Promise]. If you ever see
[object Promise] on a page you built, somebody forgot an await, and it was
probably you.
A rejected promise becomes an exception at the await. If the thing you’re
waiting for fails (here, a cook function that returns a promise, like the one the
project builds later), the await line throws an error, and an ordinary
try/catch catches it:
try {
const dish = await cook("Soufflé", 3);
console.log(dish);
} catch (error) {
console.log("No soufflé: " + error.message);
}
So errors from slow work land where errors from fast work do, which is the main reason promises replaced nested callbacks. (JavaScript reports failures with exceptions rather than return values. The Java article is the place to go deeper on exceptions.)
Two awaits in a row take turns. To wait for several things at once, start them
all, then wait. Promise.all takes a list of promises and gives you one promise
that’s fulfilled when they all are:
<!doctype html>
<title>Together</title>
<script>
function wait(ms) {
return new Promise((resolve) => setTimeout(resolve, ms));
}
async function main() {
let start = Date.now();
await wait(150);
await wait(100);
console.log("one after the other: about " + (Date.now() - start) + " ms");
start = Date.now();
await Promise.all([wait(150), wait(100)]);
console.log("both at once: about " + (Date.now() - start) + " ms");
}
main();
</script>
The first takes about 250 milliseconds, the second about 150. Nothing ran in parallel here, in the sense of two lines of your code at the same instant. Both timers counted down together while your code was paused.
The browser’s own slow operations all speak promises. The one you’ll use most is
fetch, which asks a server for something:
const response = await fetch("https://example.com/menu.json");
const menu = await response.json();
Two awaits: one for the server to start answering, one for the whole answer to arrive and be read. Talking to a real server brings in a second idea, the server’s side of the conversation, which belongs to the PHP article. This article lets a timer play the server.
The same idea, everywhere
Once you see it, you’ll find it in most languages you meet. Dart, C#, Python,
Rust, Kotlin and Swift all have something called async and await, or very close
to it, and it means the same thing: pause this function until a slow thing finishes,
and let the rest of the program carry on. The engine underneath differs. The shape
in your code doesn’t.
Event-driven programs are everywhere too. A phone app spends its life waiting for taps. A game loop waits for input and frames. A server waits for requests. The browser is just the place where you can watch one run with its lid off.
Where JavaScript lets go
Plain JavaScript checks nothing before it runs (the series introduction shows what that means), so a misspelled name in a listener stays hidden until somebody clicks the button. Event-driven code gives up a subtler guarantee as well.
Inside a single listener, nothing can interrupt you. Across an await, anything
can. While your function is paused, the event loop runs other listeners, and they
can change the very things your function was relying on. When it wakes up, the
world it remembers may be out of date.
Here is the classic version. A search box looks up each word as you type it:
box.addEventListener("input", async () => {
const word = box.value;
const meaning = await lookUp(word);
result.textContent = meaning;
});
Type “cat”. Each letter starts a lookup, so “c”, “ca” and “cat” are all in flight at once. If the answer for “ca” happens to come back last, it overwrites the answer for “cat”, and the page shows a definition for a word you’re no longer looking at. No error. No warning. Just wrong.
The fix is to check, after every await, whether the world still looks the way it
did before:
const meaning = await lookUp(word);
if (box.value !== word) {
return;
}
result.textContent = meaning;
The habit to build: treat every await as a door that someone else may have walked
through.
Beware of reaching for a framework, or for npm (the Node Package Manager, which installs other people’s JavaScript), before you need one. Most JavaScript tutorials start with React, a build tool and a few hundred downloaded packages, and you can spend a week learning those before you’ve written a single listener. Every one of those frameworks is a layer of tidy machinery on top of what you just learned: listeners, an event loop, and promises. Learn the bottom layer first, with nothing but a file and a browser. The frameworks will make much more sense, and you’ll be able to tell when you don’t need one at all, which is more often than their tutorials suggest.
A small project: the Event Kitchen
The project is a kitchen that takes orders. Each dish takes a different time to cook. You can order as much as you like while things are cooking, and dishes come out when they’re done, not when you ordered them. One dish, the soufflé, always fails, so you can see where an error goes.
The project’s two files are in
projects/javascript. Put them in a folder together, or
type them in yourself. First the page, index.html:
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>The Event Kitchen</title>
<style>
body { font-family: system-ui, sans-serif; max-width: 30rem; margin: 2rem auto; padding: 0 1rem; }
button { font-size: 1rem; margin: 0 0.25rem 0.5rem 0; }
li { margin: 0.25rem 0; }
</style>
</head>
<body>
<h1>The Event Kitchen</h1>
<p>
<button id="tea">Tea</button>
<button id="toast">Toast</button>
<button id="soup">Soup</button>
<button id="souffle">Soufflé</button>
</p>
<p id="pass">The kitchen is quiet.</p>
<ol id="tickets"></ol>
<script src="kitchen.js"></script>
</body>
</html>
Then the program, kitchen.js:
const tickets = document.querySelector("#tickets");
const pass = document.querySelector("#pass");
let cooking = 0;
function cook(dish, seconds) {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (dish === "Soufflé") {
reject(new Error("it collapsed"));
} else {
resolve(dish + ": ready");
}
}, seconds * 1000);
});
}
function showPass() {
pass.textContent = cooking === 0 ? "The kitchen is quiet." : cooking + " cooking";
}
async function order(dish, seconds) {
console.log("order in: " + dish);
const ticket = document.createElement("li");
ticket.textContent = dish + ": cooking…";
tickets.append(ticket);
cooking += 1;
showPass();
try {
ticket.textContent = await cook(dish, seconds);
} catch (error) {
ticket.textContent = dish + ": " + error.message;
}
console.log(ticket.textContent);
cooking -= 1;
showPass();
}
document.querySelector("#tea").addEventListener("click", () => order("Tea", 1));
document.querySelector("#toast").addEventListener("click", () => order("Toast", 2));
document.querySelector("#soup").addEventListener("click", () => order("Soup", 4));
document.querySelector("#souffle").addEventListener("click", () => order("Soufflé", 3));
console.log("The kitchen is open. The script has finished; the page is waiting.");
(The real file ends with a block of “Try this next…” ideas, which aren’t printed here.)
Open index.html in your browser with the console showing. Click Soup, Tea, Toast
and Soufflé, quickly, in that order. The console tells the story:
The kitchen is open. The script has finished; the page is waiting.
order in: Soup
order in: Tea
order in: Toast
order in: Soufflé
Tea: ready
Toast: ready
Soufflé: it collapsed
Soup: ready
Four orders went in, and four came out in a different order, each when its own timer finished. Here’s what to notice in the code.
cook is the slow thing. It returns a promise and settles it later, fulfilled for
most dishes and rejected for the soufflé. Its arrow function gets reject as well
as resolve, and calling reject is how a promise says it failed. In a real app this would be fetch
talking to a server; the shape of the code around it would be identical.
order is an async function, so each click starts its own copy, and each copy
pauses at its own await with its own dish and its own ticket. Four orders
means four paused functions, each one waiting for its promise, none of them in the
way of the others. That’s why the page never freezes, and why you can keep clicking.
The page changes through three calls: document.createElement("li") makes a new
list item, tickets.append puts it on the page, and setting textContent changes
the words it shows.
The soufflé’s rejection turns into an exception at the await, and the catch
writes it on the ticket. The kitchen carries on.
And cooking is the shared state that changes while functions are paused. Each
order adds one before its await and takes one away after. Watch the “cooking”
line on the page climb as you click and fall as dishes come out. Every change
happens inside one listener or one resumed function, running to completion, so the
count never gets scrambled.
The script itself finished in a few milliseconds, before you clicked anything, and said so in its last line. Everything after that was the event loop calling you.
What’s left out, and where to go next
This article left out almost all of JavaScript, on purpose. There’s nothing here
about classes, modules, the many ways to build and change a page’s elements, CSS,
or how this behaves (a topic with a reputation). There’s nothing about Node.js,
which runs JavaScript outside the browser with the same event loop underneath.
And there’s nothing about the finer workings of the queue, such as why a fulfilled
promise’s callback jumps ahead of a timer that was due first. MDN’s page on the
JavaScript execution model
covers that when you’re curious.
For JavaScript itself, the best place to keep going is MDN’s JavaScript guide, written by the people who document the browsers. When you want to go deeper on the subject of this article, read its pages on using promises and on events. And when you’re ready to have JavaScript’s types checked before it runs, the TypeScript article picks up there.
A message waiting for you
This page is a web page too, and it has been running a little JavaScript the whole time you’ve been reading. It left you a message.
Open the console right here, on this article, with F12 (or Cmd+Option+I on a Mac). Read what it says, then do what it asks. Bring one question with you: when you click the page after that, who is calling your code?
Related
- TypeScript: the same language, with its types checked before it runs.
- PHP: the server on the other end of a
fetch. - Java: exceptions, the way JavaScript reports that something failed.
- Dart: another language that leans on
asyncandawait, for drawing screens.
Tested with Firefox 153 ESR, November 2026.
The Programming Shortcut: TypeScript
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about static checking as a tool you choose.
TypeScript is JavaScript with a checker standing next to you.
That’s most of what it is. Every TypeScript program is a JavaScript program with
some notes written into it, notes that say what kind of value goes where. A tool
called tsc reads those notes, reads your code, and tells you where the two
disagree. Then it deletes the notes and hands you plain JavaScript to run.
So TypeScript doesn’t ask you to learn a new way of programming. It asks you to say out loud what you were already assuming, and then it holds you to it. And it lets you decide how much to say, and how hard it should look. That choice is what this article is about: static checking as a tool you pick up, and types as a way to design a program before you run it.
What you already have
TypeScript’s everyday code is JavaScript’s, and JavaScript’s everyday code looks
like most languages you’ve met. Variables are const and let. Functions,
if, for, while, arrays in square brackets, and objects in curly braces all
look the way you’d guess, so this article won’t slow down for any of them.
What’s new is the vocabulary for describing values:
| What you know | lux | TypeScript |
|---|---|---|
| a record | struct Parcel { kg: float } | type Parcel = { kg: number } |
| a value that might be missing | Option<int> | number | undefined |
| one of a fixed set of cases, each with its own data | enum with payloads | a union of object types with a shared tag field |
| covering every case | match, checked | switch, checked with a never trick |
| when types are checked | before every run, always | when you run tsc, then erased |
If you learned lux, you’ve already used a checker. You just never got a say in it: lux checks every program, every time, before anything runs. TypeScript hands you the switch, and a dial for how hard it looks. The rest of this article works the same whether or not you’ve ever seen lux.
Save, read, run
You’ll need Node.js, the program that runs JavaScript outside a browser. With it installed, one command gets you the checker, using npm, the package manager that comes with Node.js:
npm install -g typescript
(The TypeScript download page has the other ways.)
Make a folder, and in it a file called hello.ts with a mistake on purpose:
const greeting: string = 42;
console.log(greeting);
The : string is a type annotation: a note that says what kind of value
greeting should hold. Now open a terminal in that folder and start the
checker in watch mode:
tsc --watch hello.ts
It reads the file and answers right away:
03:33:33 PM - Starting compilation in watch mode...
hello.ts(1,7): error TS2322: Type 'number' is not assignable to type 'string'.
03:33:33 PM - Found 1 error. Watching for file changes.
Line 1, column 7: you promised a string and gave it a number. Leave that
terminal running, and look in the folder. There’s a new file, hello.js, even
though there was an error. That file comes back near the end of this article.
Fix the line to const greeting: string = "hello"; and save. The watching
terminal notices, checks again, and reports Found 0 errors. Open a second
terminal in the same folder and run what it wrote:
node hello.js
From here on, the rhythm is save, read the errors, run. The first
terminal is your checker, always watching. The second is where the program
actually runs. Every time something new appears below, try it in hello.ts and
watch the first terminal before you run anything.
The checker reads, it never runs
A checker is a program that reads your program without running it and looks for contradictions. That’s what “static” means in static checking: the code sits still while it’s examined. Nothing gets printed, nothing gets saved, no branch gets taken. Every line is read, including the ones that would never run today.
The surprise is how much it can work out with no help at all. Try this, with no annotations anywhere:
const parcel = { id: "A1", kg: 2.5 };
console.log(parcel.weight * 2);
error TS2339: Property 'weight' does not exist on type '{ id: string; kg: number; }'.
You never said what type parcel was. The checker looked at the value you gave
it and wrote the type down for itself: an object with an id that’s a string
and a kg that’s a number. This is called type inference, the checker
deducing types from the values in front of it. In plain JavaScript, that line
quietly prints NaN, short for “not a number,” and carries on.
Inference covers the inside of your code very well. Where it runs out is at the
edges, where a value arrives from somewhere the checker can’t see. A function’s
parameters are the main edge: when you write function shippingCost(kg), the
checker has no idea what callers will pass. So that’s where you write
annotations:
function shippingCost(kg: number): number {
return 4 + kg * 1.5;
}
console.log(shippingCost(2));
The : number after kg says what comes in. The : number after the
parentheses says what goes out. Inside the function, everything else is
inferred. A good rule of thumb is that you annotate the edges and let the
checker work out the middle.
How strict? You decide
Here’s a small program with a bug. find looks through an array and returns the
first match, or undefined if there isn’t one. JavaScript’s undefined means
“no value here,” and it’s the closest thing TypeScript has to an empty Option
(the idea of a value that might be missing gets its full treatment in the
Rust article). Save it as found.ts:
const ids = ["A1", "B2"];
const found = ids.find((id) => id.startsWith("C"));
console.log(found.length);
error TS18048: 'found' is possibly 'undefined'.
The checker inferred that found is string | undefined, read as “a string or
undefined.” The | builds a union type: a value that’s one of several types.
Since nothing starts with “C,” found really is undefined, and asking for its
length would crash.
Now run the same file with the checker turned down:
$ tsc --strict false found.ts
$ node found.js
TypeError: Cannot read properties of undefined (reading 'length')
No error from tsc, and a crash when it runs. With strict off, the checker
treats undefined as something that fits anywhere, so it stops asking. It also
stops complaining about parameters with no annotation, and lets them accept
anything at all.
That’s the dial. strict is a bundle of stricter checks, and since TypeScript
6.0 it’s on unless you turn it off. You can also turn its parts on and off one
at a time, with flags such as --strictNullChecks for the undefined question.
Why would anyone turn it down? Because TypeScript was built for people with
thousands of lines of JavaScript already written. Turning everything on at once
would bury them in errors, so they turn the checks up a notch at a time, file by
file, as the code gets cleaned up. Starting fresh, leave it on.
When the checker does complain, the fix is to handle the case:
const ids = ["A1", "B2"];
const found = ids.find((id) => id.startsWith("C"));
if (found === undefined) {
console.log("no match");
} else {
console.log(found.length);
}
Inside the else, the checker knows found is a string, because it followed
your if. This is called narrowing: a check in your code shrinks a union down
to the cases that are still possible. Narrowing is how a checker and an ordinary
if work together, and the rest of this article leans on it.
Types are a design you write down
So far the checker has been catching slips: a misspelled property, a missing value. That’s useful, and it’s the smaller half of the story. The bigger half is that types let you write down what your data is allowed to be, before you write any code that uses it. Then the checker holds every line to that design.
Say a shop takes three kinds of payment: cash, a card (where you keep the last four digits), or a voucher (where you keep its code). The quick way to describe that is one record with every field anyone might need:
type Payment = { kind: string; last4?: string; code?: string };
const payment: Payment = { kind: "card" };
console.log(`Card ending ${payment.last4}`);
The ? makes a field optional, and the backticks make a template string, where
${...} drops a value into the text. This passes the checker and prints Card ending undefined. Nothing is wrong according to the type, because the type allows it.
It also allows a cash payment with a card number, a voucher with no code, and a
kind of "check". The type describes a shape, but it doesn’t describe the
shop.
Here’s the design written down instead:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string };
function receipt(payment: Payment): string {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
case "voucher":
return `Voucher ${payment.code}`;
}
}
console.log(receipt({ kind: "card", last4: "4242" }));
Two new ideas are in there. First, "cash" is used as a type. A literal type
is a type with one value in it: the only string that fits "cash" is "cash".
Second, Payment is a union of three object types, each with a kind field
holding a different literal. That shared field is called the tag, and a union
told apart by its tag is a discriminated union. It’s TypeScript’s version of a
sum type, a value that’s one of a fixed set of cases, each carrying its own data
(sum types have their home in the Rust article).
Now look at what the checker knows. Inside case "card":, it has narrowed
payment to the card case, so payment.last4 is a string, guaranteed. Try to
read payment.code there and it refuses, since cards don’t have one. And the
nonsense values are gone:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string };
const payment: Payment = { kind: "card" };
console.log(payment);
error TS2322: Type '{ kind: "card"; }' is not assignable to type 'Payment'.
Property 'last4' is missing in type '{ kind: "card"; }' but required in type '{ kind: "card"; last4: string; }'.
A card without its digits can’t be written down anymore. People put this as
“make illegal states unrepresentable”: design the type so the wrong value has no
spelling, and you never have to check for it later. A misspelled tag fails the
same way. Write kind: "vouchr" and the checker says the value isn’t one of the
three, and usually suggests the one you meant.
Look back at the two Payment types. The first was a description of some JavaScript objects. The
second is a short, checkable statement of how the shop works, and you can read
it before reading a single function.
Making the checker find what you forgot
Designs change. Say the shop starts taking store credit. You add a case to the
type and move on, and somewhere in the program a switch is still handling
only the old three. Can the checker find it for you?
It can, with one small function:
type Payment =
| { kind: "cash" }
| { kind: "card"; last4: string }
| { kind: "voucher"; code: string }
| { kind: "credit"; account: string };
function unreachable(value: never): never {
throw new Error(`Unhandled case: ${JSON.stringify(value)}`);
}
function receipt(payment: Payment): string {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
case "voucher":
return `Voucher ${payment.code}`;
default:
return unreachable(payment);
}
}
console.log(receipt({ kind: "cash" }));
error TS2345: Argument of type '{ kind: "credit"; account: string; }' is not assignable to parameter of type 'never'.
never is the type with no values in it at all. Nothing fits. Each case
narrows payment a little further, and by the default, every case you handled
has been ruled out. If you handled them all, what’s left is never, and passing
it to unreachable is fine. If you missed one, what’s left is that case, and
the checker names it for you. Add a case "credit": and the error goes away.
That’s exhaustive matching: the checker proving you covered every case. Some
languages build it in (the Rust article is its home); in TypeScript
it’s a habit you choose, one default line per switch. In a big program, that
one line turns “add a case to the type” into a list of every place that needs
updating, delivered before you run anything.
Then the types disappear
Remember the hello.js that appeared even though there was an error? Here’s
what tsc writes for the receipt function above:
function receipt(payment) {
switch (payment.kind) {
case "cash":
return "Paid in cash";
case "card":
return `Card ending ${payment.last4}`;
The types are gone. This is called type erasure: the types exist only while
tsc is checking, and the program that runs has none of them. The checker
writes the JavaScript whether or not it found errors, because its job is to
advise you, not to stop you. (The "use strict" line you’ll see at the top of
its output is JavaScript’s own setting, and nothing to do with the checker’s.)
Erasure is what makes TypeScript so easy to adopt. The output is ordinary
JavaScript, so it runs anywhere JavaScript runs. Node.js will even run a .ts
file directly, by blanking out the types and running what’s left, without
checking anything. But it’s also where TypeScript gives up a guarantee you may
be used to. In a language like lux or Rust, a value that claims to be a number
is a number. In TypeScript, it’s a number if everything that touched it was
checked. Data from outside, such as a file or a network reply, wasn’t:
type Parcel = { id: string; kg: number };
const parcel: Parcel = JSON.parse('{ "id": "A1", "kg": "2.5" }');
console.log(parcel.kg + 1);
That prints 2.51. JSON.parse turns text in JSON (JavaScript Object
Notation, the most common format for sending data as text) into a value, and
the checker can’t know what the text will hold, so it calls the result any. any is a type that
switches checking off: anything fits into it, and it fits into anything. Here it
slid straight into a Parcel, and a string got treated as a number with no
complaint. The program ran with the wrong value in a field that promised better.
Beware of any. It’s the one-word way to make an error go away, and you’ll
see it all over answers online, pasted in to silence a checker someone was
tired of reading. Every any is a hole in the design, and holes spread: a value
typed any passes its blindness to everything it touches. When you truly don’t
know what something is, write unknown instead. It’s the careful sibling of
any: anything fits into it, but the checker won’t let you use it until you’ve
narrowed it with a check of your own. An error you silence with any is a bug
you’ve scheduled for later.
A parcel list that lies to you
Here’s a small program in plain JavaScript. It keeps a list of parcels, says
where each one is, and adds up their weight. Save it as parcels.js in a new
folder:
const parcels = [
{ id: "A1", status: "packed", kg: 2.5 },
{ id: "B2", status: "shipped", kg: 1.2, tracking: "1Z999" },
{ id: "C3", status: "delivered", kg: "4", tracking: "1Z123", deliveredOn: "Nov 20" },
{ id: "D4", status: "shipped", kg: 0.8 },
];
function describe(p) {
switch (p.status) {
case "packed":
return `${p.id}: packed, waiting for pickup`;
case "shipped":
return `${p.id}: on its way, tracking ${p.tracking}`;
case "deliverd":
return `${p.id}: delivered ${p.deliveredon}`;
default:
return `${p.id}: status unknown`;
}
}
let total = 0;
for (const p of parcels) {
console.log(describe(p));
total += p.kg;
}
console.log(`Total weight: ${total} kg`);
Run it with node parcels.js:
A1: packed, waiting for pickup
B2: on its way, tracking 1Z999
C3: status unknown
D4: on its way, tracking undefined
Total weight: 3.740.8 kg
No errors, and three bugs. A delivered parcel has an unknown status. A shipped
parcel has no tracking number. And the total weight is a sentence, not a number,
because one weight was written as the text "4" and + glued the rest on as
text. JavaScript did what it was told every step of the way.
Step 1: check it as it is. You don’t have to change a line to get a first opinion. Start the checker on the JavaScript file:
tsc --watch --checkJs --noEmit parcels.js
--checkJs asks it to check a JavaScript file, and --noEmit tells it not to
write any output, since this file is already JavaScript. It finds two things:
parcels.js(8,19): error TS7006: Parameter 'p' implicitly has an 'any' type.
parcels.js(24,3): error TS2365: Operator '+=' cannot be applied to types 'number' and 'string | number'.
The second error is the weight bug, found purely by inference: the checker
noticed that kg is sometimes a number and sometimes a string. Change "4" to
4 and save, and it’s gone.
The first error is the checker telling you where it’s blind. It can’t know what
p is inside describe, so it treats it as any and checks nothing there.
That’s why it missed the other two bugs. Inference has taken you as far as it
can. The rest needs a design.
Step 2: write the design down. Stop the watcher with Ctrl+C. Rename
parcels.js to parcels.ts, and add this at the top, followed by a blank line:
type Parcel =
| { status: "packed"; id: string; kg: number }
| { status: "shipped"; id: string; kg: number; tracking: string }
| { status: "delivered"; id: string; kg: number; tracking: string; deliveredOn: string };
That’s the business rule, in four lines: a parcel is in one of three states, and
shipped and delivered parcels always have a tracking number. Now tell the
program about it. Change the first line of the list to
const parcels: Parcel[] = [, which says the array holds parcels, and give
describe its annotations, function describe(p: Parcel): string {. Then start
the checker on the new file:
tsc --watch parcels.ts
parcels.ts(10,3): error TS2322: Type '{ id: string; status: "shipped"; kg: number; }' is not assignable to type 'Parcel'.
Property 'tracking' is missing in type '{ id: string; status: "shipped"; kg: number; }' but required in type '{ status: "shipped"; id: string; kg: number; tracking: string; }'.
parcels.ts(19,10): error TS2678: Type '"deliverd"' is not comparable to type '"delivered" | "packed" | "shipped"'.
(It also reports two errors on line 20 about a type called never, which go
away with the typo.) There are both remaining bugs. Parcel D4 claims to be
shipped without a tracking number, and "deliverd" isn’t a status that exists.
Give D4 a tracking number, tracking: "1Z456", fix the spelling to
"delivered", and save. The checker has two more:
parcels.ts(20,38): error TS2551: Property 'deliveredon' does not exist on type '{ status: "delivered"; id: string; kg: number; tracking: string; deliveredOn: string; }'. Did you mean 'deliveredOn'?
parcels.ts(22,19): error TS2339: Property 'id' does not exist on type 'never'.
The first is a third bug that was hiding behind the second: the wrong
capitalization of deliveredOn. Fix it. The second is the checker pointing out
that the default can’t happen anymore, because every status is handled. That’s
your cue for the never trick. Add the unreachable function above describe:
function unreachable(p: never): never {
throw new Error(`Unhandled parcel: ${JSON.stringify(p)}`);
}
and make the default return unreachable(p);. Save, and the first terminal
says Found 0 errors. Run the result in the second terminal with
node parcels.js:
A1: packed, waiting for pickup
B2: on its way, tracking 1Z999
C3: delivered Nov 20
D4: on its way, tracking 1Z456
Total weight: 8.5 kg
parcels.js is back, and this time tsc wrote it: your program with the types
erased.
Step 3: change the design. Customers start sending things back. Add a fourth
case to the type, and move the ; from the old last line to this new one:
| { status: "returned"; id: string; kg: number; reason: string };
and a returned parcel to the list, { id: "E5", status: "returned", kg: 3.1, reason: "wrong size" },. Save. The checker points straight at the default in
describe, naming the "returned" case you haven’t handled. Add it:
case "returned":
return `${p.id}: sent back (${p.reason})`;
Zero errors, and node parcels.js prints five parcels and a total of 11.6 kg.
You changed the design first, and the checker walked you to the code that had to
follow. The finished file is in
projects/typescript/parcels.ts, with
more experiments at the bottom.
What’s left out
A lot of TypeScript isn’t here. Generics, which let one type or function work
across many types, are a big part of real TypeScript; they’re the subject of the
Swift article, and TypeScript’s work the same way in spirit.
interface, which overlaps heavily with type, is skipped, and so are classes,
modules, tsconfig.json files, and the long list of individual strict flags.
There’s also a whole type-level programming language hiding inside TypeScript,
with mapped and conditional types, which you won’t need for a long time and may
not need at all.
All of it is skipped because none of it changes the idea. You choose a checker, you choose how strict it is, you write your design as types, and you let it hold your code to that design until the types are erased.
When you want more, the TypeScript Handbook is written by the people who make the language, and its chapter on narrowing picks up where this article stops.
One last thing to try
Go back to your finished parcels.ts and run the checker one more time, with a
flag that asks it to show its work:
tsc --declaration parcels.ts
Next to parcels.js, there’s now a parcels.d.ts. Read it. It holds every type
in your program, including the ones you never wrote, like the type of total.
Then open parcels.js and look for those same types. Bring this question: which
of the types in the first file did the checker work out on its own, and where
did all of them go?
Related
- Rust, for values that might be missing, sum types and exhaustive matching, built into the language.
- Swift, for generics.
- JavaScript, for the language underneath all of this.
Tested with TypeScript 7.0.2 and Node.js 26.13.1, November 2026.
The Programming Shortcut: PHP
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about request and response.
A little code inside a web page
In 1994 a programmer named Rasmus Lerdorf wanted to keep track of visits to his online résumé. He wrote a few small tools for the job and called them Personal Home Page Tools. He shared them, they grew support for guestbooks and forms, and a few rewrites later the result was a language. It still carries the initials.
So PHP wasn’t designed as a general-purpose language that later learned about the web. It started as a way to put a little code inside a web page, and it still is. Most languages give you a program that produces output. PHP gives you a page, with a program tucked inside it.
That makes PHP the clearest place to see how every website works. Behind any page you have ever loaded, a program received a message from your browser and sent one back. Big frameworks in big languages wrap that exchange in layers. PHP doesn’t bother. The exchange is right there in front of you, and you can watch it happen in your own terminal.
What you already have
You already know variables, decisions, loops, functions, arrays and records, so here they are in PHP’s spelling, and then we can leave them alone:
| What you know | lux | PHP |
|---|---|---|
| a variable | let name = "Ada" | $name = "Ada"; (every variable starts with $) |
| joining text | "Hi, " + name | "Hi, " . $name (a dot, not a plus) |
| printing | print(...) | echo ...; and it goes to the visitor, not your screen |
| reading input | input("Name? ") | $_GET['name'] and $_POST['name'], filled in before your code runs |
| a value that might be missing | Option | null, with ?? to supply a fallback |
| a record | struct | an array with named keys: ['name' => 'Ada'] |
| things that go wrong | Result | exceptions, or false from older functions |
| when types are checked | before running | when the line runs |
The fourth row is where this article lives. Everything else carries over.
Your own web server, in one line
You need PHP itself. On Debian or Ubuntu, that’s:
sudo apt install php-cli
For macOS, Windows and everything else, php.net/downloads
has instructions. Check that it worked with php -v.
Now make an empty folder, and in it a file called hello.php:
<?php
$name = "world";
?>
<h1>Hello, <?= $name ?>!</h1>
Two things in there are new. Anything between <?php and ?> is PHP code.
Everything outside those tags is sent out as it is, with no processing at all.
And <?= $name ?> is shorthand for “echo this value right here”.
In a terminal, from that folder, start PHP’s built-in web server:
php -S localhost:8000
localhost means “this computer”, and 8000 is a port, a numbered door on it
that the server listens at. Open a browser and visit
http://localhost:8000/hello.php. You’ll see a big “Hello, world!”
Now look back at the terminal. A few new lines appeared there, and one of them looks like this:
[Sun Nov 22 15:34:22 2026] [::1]:35704 [200]: GET /hello.php
That line is the server telling you it just ran your program for someone. Keep that terminal where you can see it. It’s the most useful window in this article.
Now try it. Change "world" to your own name, save
the file, and refresh the browser. There’s no compile step and no restart. Every
refresh runs your file again, from the top, with whatever you last saved.
The built-in server is a tool for your own machine. The PHP manual says it shouldn’t be used on a public network, and when you put a site online for real, a different server does this job. For learning, it’s all you need.
A conversation in two messages
When you refreshed that page, your browser and the server had a short conversation. It went like this.
The browser sent a request. A request is a small piece of text that says what the browser wants:
GET /hello.php HTTP/1.1
Host: localhost:8000
The first word is the method, which says what kind of request this is. GET
means “please give me this”. Then comes the path, the part of the address after
the server’s name. The lines after that are headers, labeled bits of extra
information. A real browser sends a dozen or so headers, describing itself and
what it can accept.
The server ran hello.php and sent back a response, which has the same shape:
HTTP/1.1 200 OK
Content-type: text/html; charset=UTF-8
<h1>Hello, world!</h1>
The first line holds a status code: 200 means everything went fine. You’ve
met its cousin 404, which means “no such page”. Then come the response’s
headers, then one blank line, then the body, which is the thing the browser
shows you.
The rules for this conversation are called HTTP, the HyperText Transfer Protocol. A protocol is an agreement about who says what, in what order. HTTP has a lot of details, and the overview on MDN Web Docs, Mozilla’s reference for the web, is a friendly place to read them. But its heart is the two messages you just saw. One request in, one response out.
Every echo in your PHP file, and every bit of HTML outside the tags, becomes
part of that response body. That’s what the shortcut table meant when it said
echo goes to the visitor. Your program doesn’t talk to a screen. It writes a
reply.
Your program lives for one request
Here’s the part that surprises people. Save this as count.php in the same
folder:
<?php
$visits = 0;
$visits = $visits + 1;
?>
<p>This is visit number <?= $visits ?>.</p>
Visit http://localhost:8000/count.php and refresh it a few times. Watch the
terminal: a new line for every refresh. Watch the page: visit number 1. Visit
number 1. Visit number 1.
Of course it says 1. The program sets $visits to 0 and adds 1. But think about
what that means. In most programs you’ve written, a variable lives as long as the
program does, and a program lives until it’s done. This program is done well under a
millisecond after each request arrives. The server reads the request, starts
your file fresh at the first line, runs it to the end, sends whatever it printed,
and throws away every variable you made. The next request gets a brand-new run
that has never heard of the last one.
A program that keeps nothing from one request to the next is called stateless. State is whatever a program remembers: the values in its variables, the things it has counted, the stage it has reached. A PHP page starts every request with none.
If you learned lux, you know the opposite shape well. A lux program owns its whole
run: it starts, asks questions with input(), keeps its variables while it loops,
and ends when it decides to. A PHP page lives for one request and forgets
everything. (If you ever wrote a lux file for a host, you’re halfway there. The
host called your functions and kept what they handed back. A web server is a host
that calls your page and keeps nothing.)
This isn’t a PHP quirk. HTTP itself was designed this way. Its specification calls it “a stateless protocol, meaning that each request message’s semantics can be understood in isolation.” Every request has to make sense on its own, because the protocol doesn’t count on the server remembering the one before. PHP takes that design and builds its programs to match.
What you need arrives with the request
If a program can’t remember anything, how does it know anything? It reads the request. Everything your page needs to do its job has to come in with the request or be fetched from somewhere while it runs.
The simplest place to carry information is the address itself. Try this as
greet.php:
<?php
$name = $_GET['name'] ?? 'stranger';
?>
<h1>Hello, <?= htmlspecialchars($name) ?>!</h1>
Visit http://localhost:8000/greet.php and you’ll be greeted as a stranger. Now
visit http://localhost:8000/greet.php?name=Ada. The bit after the ? is the
query string, a list of names and values glued onto the address. PHP reads it
before your code starts and puts it in $_GET, an array with a key for each name.
Change the name in the address bar and press Enter. It’s the same edit and refresh,
only this time you’re editing the request instead of the file.
$_GET is one of PHP’s superglobals: arrays that PHP fills in from the request
before the first line of your file runs, and that every part of your program can
see. There’s one for each part of the request you might care about.
The ?? says “use the left side if it exists and isn’t null, otherwise use the
right side”. Without it, a visit with no query string would ask for a key that
isn’t there. Requests come from strangers, and anything in one might be missing.
(Some languages make you deal with missing values before your program will even
run. The Rust article shows how; in PHP, ?? is your polite fallback.)
And htmlspecialchars is there for a reason that gets its own section below. For
now, wrap it around anything that came from a request before you echo it.
Forms are requests you fill in
Typing a query string by hand gets old. A form is HTML that builds the request
for you. The visitor fills in the fields, presses the button, and the browser
sends a new request carrying what they typed. Put this in form.php:
<?php
$name = $_POST['name'] ?? '';
?>
<form method="post">
<input name="name" value="<?= htmlspecialchars($name) ?>">
<button>Send</button>
</form>
<?php if ($_SERVER['REQUEST_METHOD'] === 'POST'): ?>
<p>The server received: <?= htmlspecialchars($name) ?></p>
<?php endif; ?>
Load the page, type something, and press Send. In the terminal you’ll see two
requests: first a GET /form.php that fetched the empty form, then
a POST /form.php that sent it back filled in.
POST is the other common method. Where GET carries its values in the address,
POST carries them in the request body, below the headers, where they don’t show
up in the address bar or the browser’s history. The usual rule is that GET
asks for something and POST changes something. A search is a GET. Signing up,
paying, or leaving a comment is a POST. PHP puts posted values in $_POST, and
$_SERVER['REQUEST_METHOD'] tells you which kind of request this run is
answering.
Look at the input box after you press Send. It still holds what you typed. That
isn’t the browser remembering, and it isn’t PHP remembering either. Your program
read the posted name out of the request and wrote it back into the new page’s
value. When a stateless program seems to remember something, this is usually
how: the information came in with the request, and the program sent it back out.
Now press refresh on that page. Your browser asks whether you want to send the
form again. That’s not a bug. The page you’re looking at was the answer to a
POST, and refreshing means repeating the request that made it. The project
below shows the standard way around this.
Where memory goes when the program can’t keep it
Real sites remember things: who you are, what’s in your cart, what everyone wrote yesterday. Since the program can’t hold any of it, the memory has to live somewhere outside the program. There are three places it can go.
It can ride in the request itself, as you just saw. A query string, a form field, or a hidden field (a form field the visitor doesn’t see) carries information from one page to the next. The catch is that the visitor’s browser holds it, and the visitor can change it.
It can live in a cookie. A cookie is a small named value the server asks the browser to keep. The server sends it in a response header, and from then on the browser sends it back in a header with every request to that site. Here’s the counter again, fixed:
<?php
$visits = (int) ($_COOKIE['visits'] ?? 0) + 1;
setcookie('visits', (string) $visits);
?>
<p>This is visit number <?= $visits ?>.</p>
Save it over count.php and refresh a few times. Now it counts. The program still
forgets everything at the end of each run. The browser is doing the remembering,
and handing the count back with each request. Open the same page in a private
window and you start again at 1, because that window has its own cookies.
Notice where setcookie sits: at the very top, before any HTML. A cookie travels
in a header, and headers come before the body in the response. Once your program
has started writing the body, the headers have gone. Move the setcookie call
below the <p>, inside its own <?php ?> tags, and start the server as
php -d output_buffering=0 -S localhost:8000. Now PHP complains in the server’s
terminal: Cannot modify header information - headers already sent. (Without that
flag, many installs quietly hold back the first few kilobytes of the body in a
buffer, so the late header still fits and you see no warning. Don’t count on it.) The shape of the response is showing through
the language.
Or the memory can live on the server, in a file or a database. Each run reads what it needs when it starts and writes back what changed before it ends. This is the only place for things that belong to everyone rather than to one visitor. A cookie can count your visits, but it can’t count the site’s, because it lives in your browser and nobody else’s. The project uses a file.
(PHP also has sessions, which combine the last two: a cookie holds a random ID, and the server keeps the data under that ID. You’ll meet them soon after this article, and now you know what they’re made of.)
Why forgetting is a feature
At this point, statelessness might sound like a handicap that the web forces on you. It’s closer to the opposite.
Because each run starts clean, nothing piles up. A bug that corrupts a variable ruins one response, and the next request starts fresh. A crash takes down one visitor’s page, not the site. And because no run holds anything another run needs, a busy site can start many copies of the same program at once, even on different machines, and send each request to whichever copy is free. None of them needs to know what the others are doing. This design has a name, shared-nothing, and it’s why a PHP site can handle more visitors by adding more machines.
The price is the one you’ve been paying all along: you have to decide where every piece of state lives, and carry it there on purpose.
Once you know this shape, you’ll see it far beyond PHP. A web program in almost any language boils down to a function that takes a request and returns a response. Go, Python, Java and JavaScript on a server all hand you a request object and ask you for a response. In PHP, the whole file is that function.
The browser side of the conversation works differently. A page in the browser stays open and waits for clicks and keypresses, running a little code each time something happens. That’s event-driven programming, and the JavaScript article is its home. A PHP page never waits. It runs, answers, and ends.
Where PHP trusts you
PHP gives up two guarantees you may be used to.
The first is about types. PHP lets you declare them, but it checks them only when
a line runs. A mistake in a branch that never runs stays quiet until the day it
does. Turn on strict checking with the declare line at the top, and this stops
with a TypeError the moment the call happens, not before:
<?php
declare(strict_types=1);
function shout(string $text): string {
return $text . "!";
}
echo shout("ready"), "\n";
echo shout(42), "\n";
The first line prints ready!. The second line fails. For a web page, that means
a request that takes an unusual path can find a mistake that every other request
walked past. The introduction runs the same experiment across
several languages.
The second is about text. PHP doesn’t know which text you wrote and which text a
stranger typed. To PHP, $_GET['name'] is a string like any other, and if you
echo it into the page, the browser treats it as part of your HTML. Someone who
sends a “name” containing a <script> tag gets their code running on your page,
in every visitor’s browser that shows it. This is called cross-site scripting.
htmlspecialchars is the fix. It escapes the characters that mean something in
HTML, turning < into < and so on, so the browser shows them as text instead
of obeying them:
<?php
$name = "<script>alert('hi')</script>";
echo htmlspecialchars($name), "\n";
That prints <script>alert('hi')</script>, which a browser
shows as harmless text.
Beware of old tutorials that skip escaping and prepared statements. PHP has
been around since the 1990s, and the web is full of PHP examples that echo
$_GET straight into a page, or paste it straight into a database query. The
second mistake is called SQL injection (SQL, Structured Query Language, is what databases speak), and the fix is a prepared statement,
which sends the query and the visitor’s values to the database separately so the
values can never become part of the command. Both mistakes look fine when you test
them with your own name. Both become disasters when a stranger tests them for you.
If a tutorial echoes request data without escaping it, or
builds a query by gluing strings together, close the tab. It doesn’t matter how
clear the rest of it is. There are plenty of tutorials that get this right.
A guestbook
Fittingly for a language that started with one, the project is a guestbook: a page
where visitors leave their name and a message, and everyone sees what everyone
wrote. It’s one file,
projects/php/index.php. From that folder, run:
php -S localhost:8000
Then visit http://localhost:8000/. The server finds index.php on its own when
the address names a folder, the way it would find index.html.
Sign the book. Leave the message empty and try again. Sign it once more with a
message like <em>hello</em>. Then open the file, and keep the terminal in view
while you read. The guestbook holds every kind of state from this article.
The entries live in a file. Each time someone signs, the program adds one line to
guestbook.txt, a record encoded as JSON (JavaScript Object Notation, a common
text format for structured data). Each time anyone loads the page, the program
reads every line back. Nothing about the entries survives in the program between
requests. They survive on disk, so everyone sees the same book.
Your name lives in a cookie. After you sign, the response sets a name cookie,
and the next time you load the page, the program reads it back from $_COOKIE
and fills in the name field for you. Open the page in a private window and the
entries are all there, but your name isn’t. Different state, different home.
A mistake lives in the request. If you leave a field empty, the program doesn’t
save anything. It answers with status code 400, “bad request”, and a page that
contains your own words, read out of $_POST and written back into the form, so
you don’t have to type them again. Nothing was remembered. Your words made the
round trip.
Now sign once more and watch the terminal. One signature makes two requests:
[303]: POST /
[200]: GET /
The POST carried your signature. Instead of
answering it with a page, the program answered with status 303, “see other”,
plus a Location header pointing back at /. That tells the browser to go and
fetch that address with a fresh GET, so the page you end up looking at is the
answer to a harmless GET. Refresh it as often as you like; nothing is sent
twice. This pattern is called Post/Redirect/Get, and it’s how most sites keep a
refresh from paying for something twice.
Find the <em>hello</em> you signed with. It shows up as text, angle brackets and
all, because the program passes everything a visitor wrote through e(), a
one-line function wrapped around htmlspecialchars. Every value that came from a
request goes through it on the way out.
At the bottom of the page is the time it was built. Refresh, and it changes. Every page you see is a new answer to a new request, written a moment ago by a program that has already stopped running.
The end of index.php has a list called “Try this next…” with more experiments.
The first one shows you what the browser does when Post/Redirect/Get goes
missing.
What’s left out, and where to go next
This article left out a lot of PHP. There’s nothing here about
databases (PHP’s built-in way to reach them is called PDO, PHP Data Objects, and it does prepared
statements well), sessions beyond a paragraph, classes, Composer (PHP’s tool for
using other people’s packages), or frameworks like Laravel and Symfony. Nothing
either about how PHP runs on a real server, where a production web server hands
requests to PHP instead of php -S doing it all. Every one of those is built on
the request and response you just learned, so none of them should feel like
magic when you meet them.
The PHP manual is the place to go next. It’s at php.net/manual, it has a short tutorial of its own, and every function page ends with notes and examples. When you want to know what a superglobal holds, its page in the manual will tell you.
See what the browser saw
Load your guestbook in the browser, right-click the page and choose View Page Source. (Safari shows that item once its developer features are turned on in its settings.) Bring this question with you: where did the PHP go?
Related
- JavaScript: event-driven programming, the browser’s side of the conversation.
- Rust: values that might be missing, and a language that makes you handle them before it runs.
- The introduction: when types are checked, with the same experiment in five languages.
Tested with PHP 8.4.28, November 2026.
The Programming Shortcut: Testing
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about testing: writing code that checks your code.
You already test your code. You have done it since your first program.
You write a function, you run the program, and you look at what it printed. Is that the right number? Does the message read properly? If it looks wrong, you fix something and run it again. That looking is testing. It’s careful, it works, and it has one weakness: it only happens while you are watching, and only for the things you remember to look at.
A test is that same act written down. It’s a small piece of code that calls your code with an input you chose, compares the answer with the answer you expected, and complains if they differ. Once it’s written, the computer does the looking, every time, for every case you ever thought of, in well under a second. You stop re-checking by eye things you already checked last week.
The rest of this piece is about doing that well. Testing is a working habit, not
a language feature, so the idea isn’t tied to a language. This piece uses Go,
because Go builds testing into its own command and keeps it plain. There is no
testing library to choose, no configuration file, no plugin. You write a function
with a particular name in a file with a particular name, and you type go test.
If you don’t have Go yet, the
installer and instructions are here. You don’t need to know Go to follow along. If you can read a function and an if,
you can read every test in this piece.
A test is just a program that checks
Before any testing tool appears, here’s a test with no tool at all. It’s an
ordinary Go program. The function count is supposed to say how many of something
there are: “3 files”, “1 file”. The rest of the program checks it.
package main
import (
"fmt"
"os"
)
func count(n int, word string) string {
return fmt.Sprintf("%d %ss", n, word)
}
func main() {
got := count(1, "file")
want := "1 file"
if got != want {
fmt.Printf("count(1, \"file\") = %q, want %q\n", got, want)
os.Exit(1)
}
fmt.Println("ok")
}
(fmt.Sprintf builds a string from a pattern, the way printf or an f-string
does. %d is a number, %s is a string, %q is a string shown in quotes.)
Save it as main.go and run it with go run main.go. It prints:
count(1, "file") = "1 files", want "1 file"
exit status 1
Look at the shape, because every test you will ever write has it. You call the code with an input you picked. You hold the answer you got next to the answer you want. If they differ, you say so loudly, with enough detail to know what went wrong, and you end with a failing status so that whatever ran you knows too.
That’s it. Testing tools add convenience on top of this shape: a standard place to put the checks, a way to run all of them with one command, a tidy report. None of them change the shape.
Notice also that this check found a real bug. count always adds an “s”, and one
file isn’t “1 files”. You might have spotted that by reading the code. You might
not have, on a busy day, in a longer function. The check doesn’t get busy.
Edit, then go test
Go’s version of this lives in its own files, so your checks never get mixed into your program. Make a folder for a small package (Go’s word for a folder of code that belongs together) and give it a module name, which is how Go identifies a project:
mkdir plural
cd plural
go mod init plural
Now two files. The first is the code, plural.go:
package plural
import "fmt"
func Count(n int, word string) string {
return fmt.Sprintf("%d %ss", n, word)
}
(The capital C matters in Go: names that start with a capital letter can be used from outside the package.)
The second is the test, plural_test.go:
package plural
import "testing"
func TestCount(t *testing.T) {
got := Count(3, "file")
want := "3 files"
if got != want {
t.Errorf("Count(3, \"file\") = %q, want %q", got, want)
}
}
Three conventions do all the work. A file whose name ends in _test.go is a test
file: go test compiles it, and an ordinary build leaves it out. A function whose
name starts with Test and takes a *testing.T is a test. And t.Errorf is how a
test complains: it prints your message and marks the test as failed.
Run it:
$ go test
PASS
ok plural 0.002s
Edit the code or the tests, type go test, read the answer. It’s the same rhythm
you already have when you run a program and look at the output, with the looking
done for you. You will come back to it after every change in this
piece.
Add -v (for “verbose”) to see each test by name as it runs:
$ go test -v
=== RUN TestCount
--- PASS: TestCount (0.00s)
PASS
ok plural 0.001s
Red first
The test passes, and the bug from the first section is still sitting in Count.
Of course it passes: it only asks about three files. A test can only find the
mistakes it asks about.
So ask. Add a second test to plural_test.go, below the first:
func TestCountOne(t *testing.T) {
got := Count(1, "file")
want := "1 file"
if got != want {
t.Errorf("Count(1, \"file\") = %q, want %q", got, want)
}
}
Run it again:
$ go test
--- FAIL: TestCountOne (0.00s)
plural_test.go:17: Count(1, "file") = "1 files", want "1 file"
FAIL
exit status 1
FAIL plural 0.002s
This is good news, and you’ll learn to feel that way about it. The failure names the test, the file and line, the input, what came back and what should have. That’s a better bug report than most people write by hand.
Now fix the code:
func Count(n int, word string) string {
if n == 1 {
return fmt.Sprintf("%d %s", n, word)
}
return fmt.Sprintf("%d %ss", n, word)
}
Run go test again, and it says PASS.
What just happened has a name among programmers: red, green. Red is the failing test, green is the passing one, after the names many test tools give their colors. Writing the test first, watching it fail, and only then fixing the code proves two things at once. It proves the bug was real, and it proves the test can tell the difference. A test that has never failed in front of you hasn’t shown you either.
The test also stays. From now on, if anyone (including you, six months from now)
breaks the one-file case, go test says so the next time it runs. A test written
to catch a bug that already happened once is called a regression test, because it
stops the code from regressing, sliding back to a state it was in before. Bugs do come
back, usually when someone tidies up the code that fixed them.
Many cases, one test
You now have two tests that are the same five lines with different numbers in them. A third would make three. When tests repeat like that, the thing that varies is the data, so make the data the visible part.
This is called a table-driven test: a list of cases, each with its inputs and the answer you want, and one loop that checks them all. Replace both tests with this one:
func TestCount(t *testing.T) {
cases := []struct {
n int
word string
want string
}{
{3, "file", "3 files"},
{1, "file", "1 file"},
{0, "file", "0 files"},
{2, "box", "2 boxes"},
}
for _, c := range cases {
got := Count(c.n, c.word)
if got != c.want {
t.Errorf("Count(%d, %q) = %q, want %q", c.n, c.word, got, c.want)
}
}
}
The list is a slice (Go’s growable array) of records that have no name of their
own, written out in place: each {3, "file", "3 files"} is one row. If your language would use an array
of objects or tuples here, it’s the same thing.
Run it:
$ go test
--- FAIL: TestCount (0.00s)
plural_test.go:19: Count(2, "box") = "2 boxs", want "2 boxes"
FAIL
exit status 1
FAIL plural 0.002s
Look at what that table did. Adding a case cost one line, so you added the cases that came to mind: zero, which English treats as plural, and a word that doesn’t just take an “s”. The second one failed. You’d never have written five more lines to check “box”. You will happily write one.
Here’s a fix that handles the common endings. It needs the strings package, so
this is the whole of plural.go now:
package plural
import (
"fmt"
"strings"
)
func Count(n int, word string) string {
if n == 1 {
return fmt.Sprintf("%d %s", n, word)
}
for _, ending := range []string{"s", "x", "z", "ch", "sh"} {
if strings.HasSuffix(word, ending) {
return fmt.Sprintf("%d %ses", n, word)
}
}
return fmt.Sprintf("%d %ss", n, word)
}
Run go test, and it’s green.
Then think about “mouse”. Or “child”. Your function says “2 mouses”, and now you
have a choice to make: teach it more English, take the plural form as a second
argument, or decide that this function is for simple words and say so. A test is
where you write that decision down. Add {2, "mouse", "2 mouses"} and you’ve
recorded that this is known and accepted. Add {2, "mouse", "2 mice"} and you’ve
committed to fixing it. Either way, the next person to read the tests knows what
the function promises, without reading its code.
That last point is the quiet reason tests matter beyond catching bugs. The table is
the clearest description of what Count does that exists anywhere. It’s a
description that can’t go out of date, because the moment it stops being true,
go test fails.
Choosing what to test
You can’t test every input. Count takes any number and any word; there are more
combinations than there are atoms to write them on. So every test is a sample, and
the skill is in choosing the sample.
Bugs gather at edges. When you pick cases, reach for the places where the behavior changes or where the code has to make a decision: zero, one and many; the first item and the last; an empty string; a value exactly at a limit and one past it. These are called edge cases or boundary cases, and most of your rows should be them. The middle of the range almost always works. That’s where you tried it by hand.
Look at the shape of the code, too. Every if is a place where two kinds of input
get different treatment, and each kind deserves at least one row. Count has a
branch for one, a branch for the special endings, and a fallthrough. The table above
reaches all three.
And test what the code promises, not how it keeps the promise. Every test in this
piece calls Count and looks at its answer. None of them peek at how it builds the
string. That means you can rewrite the inside of Count any way you like (with a
switch, with a map of endings, with something cleverer) and the tests still tell
you whether it works. Changing how code is written without changing what it does is
called refactoring, and tests are what make it safe. Without them, every tidy-up
is a small gamble.
Against the grain
Some languages and testing libraries give you a vocabulary of assertions, special
functions that check something and fail the test if it’s false: assertEqual(a, b),
expect(a).toBe(b), assert a == b. Go has none of them. You write an ordinary
if, and you write the failure message yourself.
That feels primitive the first time, and it’s on purpose. The test is plain Go, so
there’s nothing new to learn, and the message says what you decided it should say.
The cost is that writing a good message is your job. A test that fails with wrong answer has thrown away the information you need. A test that fails with
Count(2, "box") = "2 boxs", want "2 boxes" has fixed half the bug for you. Go’s
habit of writing the call, then what you got, then what you want, carries into any
language.
Go also gives you two ways to fail. t.Errorf records the failure and carries on,
so one run can report every row in a table that’s wrong. t.Fatalf records it and
stops that test immediately, which you want when going on makes no sense, such as
when the setup the rest of the test needs didn’t work.
The deeper thing to give up is a guarantee you may have been hoping for. Passing tests don’t prove a program is correct. They prove it’s correct for the cases you wrote. A bug that gets past a green test run is in a case nobody thought to check. Tests make you much more confident; they never make you certain.
Beware of a test you have never seen fail. It’s an easy way for a test to go
wrong, and an invisible one: a test with a typo that compares a value to itself, a
loop over an empty table, a check on the wrong variable. Each of these passes
forever and checks nothing. So make every new test fail once, on purpose, before you
trust it. If you wrote it for a bug, run it before the fix. If you wrote it for
working code, break the code for a moment (change a 1 to a 2, flip a <) and
watch the test catch it. Thirty seconds, every time. The alternative is a green
report you can’t believe, which is worse than no report, because it looks like one
you can.
A small project: which version is newer?
Software versions look like 1.9.0 and 1.10.2, and programs compare them all the
time to decide whether an update is available. It looks like a job for ordinary
string comparison. Here’s the version you might write in a hurry:
func Newer(a, b string) bool {
return a > b
}
And here’s one row of a table that tests it:
{"1.10.0", "1.9.0", true},
It fails. Strings compare character by character, and at the third character "1"
comes before "9", so as text "1.10.0" sorts before "1.9.0". Version 1.10 is
newer, and the hurried function says it’s older. Every test in the middle of the
range would have passed, which makes it an easy bug to ship. It’s a boundary case:
the first time a part of the version reaches two digits.
The project does the job properly, and the tests are most of the project. Make a folder and a module:
mkdir versions
cd versions
go mod init versions
The code goes in versions.go. Compare returns -1 if the first version is older,
1 if it’s newer, and 0 if they’re the same. It splits each version on the dots,
turns each part into a number, and compares the numbers in order, so “1.2” and
“1.2.0” count as the same version:
package versions
import (
"fmt"
"strconv"
"strings"
)
func Compare(a, b string) (int, error) {
as, err := parts(a)
if err != nil {
return 0, err
}
bs, err := parts(b)
if err != nil {
return 0, err
}
for i := 0; i < max(len(as), len(bs)); i++ {
x, y := at(as, i), at(bs, i)
if x < y {
return -1, nil
}
if x > y {
return 1, nil
}
}
return 0, nil
}
func parts(version string) ([]int, error) {
var numbers []int
for _, field := range strings.Split(version, ".") {
n, err := strconv.Atoi(field)
if err != nil || n < 0 {
return nil, fmt.Errorf("%q is not a version number", version)
}
numbers = append(numbers, n)
}
return numbers, nil
}
func at(numbers []int, i int) int {
if i < len(numbers) {
return numbers[i]
}
return 0
}
Compare returns two values: the answer, and an error that is nil when nothing
went wrong. That’s Go’s way of reporting a failure as an ordinary value instead of
crashing (the Rust piece explains errors as values in full). It matters
here because something like "1.x" isn’t a version at all, and the only sensible
answer to “is 1.x newer than 1.0?” is “that isn’t a version”. strconv.Atoi
turns text into an integer and reports an error when it can’t.
The tests go in versions_test.go:
package versions
import "testing"
func TestCompare(t *testing.T) {
cases := []struct {
a, b string
want int
}{
{"1.2.0", "1.1.0", 1},
{"1.1.0", "1.2.0", -1},
{"1.2.0", "1.2.0", 0},
{"2.0.0", "1.9.9", 1},
{"1.10.0", "1.9.0", 1},
{"1.2", "1.2.0", 0},
{"1.2.1", "1.2", 1},
{"0.9", "0.10", -1},
}
for _, c := range cases {
got, err := Compare(c.a, c.b)
if err != nil {
t.Errorf("Compare(%q, %q) gave an error: %v", c.a, c.b, err)
continue
}
if got != c.want {
t.Errorf("Compare(%q, %q) = %d, want %d", c.a, c.b, got, c.want)
}
}
}
func TestCompareRejectsNonsense(t *testing.T) {
for _, bad := range []string{"", "1..2", "1.x", "v1.2", "1.-2"} {
if _, err := Compare(bad, "1.0"); err == nil {
t.Errorf("Compare(%q, \"1.0\") gave no error", bad)
}
}
}
Read the table before you run it, row by row, because each row is there for a
reason. The first three are the plain middle: newer, older, equal. Then the edges:
a change in the first part that outweighs bigger numbers later, the two-digit part
that broke the hurried version, versions of different lengths in both directions,
and the same two-digit trap one place over. The second test covers the other kind
of edge, input that should be refused: nothing at all, an empty part, letters, a
leading v, a negative number.
Run it:
$ go test -v
=== RUN TestCompare
--- PASS: TestCompare (0.00s)
=== RUN TestCompareRejectsNonsense
--- PASS: TestCompareRejectsNonsense (0.00s)
PASS
ok versions 0.002s
Green. Don’t trust it yet. Break something on purpose: in at, change return 0
to return 1, and run go test again. The rows comparing versions of different
lengths go red, and nothing else does. Put it back. Now try changing x < y to
x <= y and predict, before you run it, which rows will catch that. If you guessed
right, you understand the table. If you didn’t, the failures will show you
something about the code you hadn’t noticed.
Then ask Go how much of the code the tests touched:
$ go test -cover
PASS
coverage: 95.7% of statements
ok versions 0.003s
Coverage is the share of the code’s statements that ran at least once during the
tests. It’s a useful question with a misleading number. The missing few percent
here is a real gap: no test passes a bad version as the second argument, so that
return never runs. But 100% wouldn’t mean the code is right. It would mean every
line ran, not that every line was checked. Delete the if got != c.want check
from TestCompare and change got to _ in the line above it, so that it calls
Compare on every row and never looks at the answer, and coverage still says 95.7%. Use coverage to find code no test reaches, and use
your own judgment, edge by edge, for the rest.
What’s left out, and next
This piece left a lot out, so that one idea could stand clearly. Go’s
testing package does much more: subtests, which give each row of a table its own
name with t.Run so you can run one with go test -run; benchmarks, which
measure how fast code runs; fuzzing, where Go invents inputs for you and hunts for
ones that break your code; and examples, tests that double as documentation.
There are also whole schools of thought about testing that this piece skipped:
mocks and fakes that stand in for databases and networks, the different sizes of
test from a single function up to a whole running system, and test-driven
development, which turns “red first” into a way of designing code. Each makes more sense
once the basic habit is yours.
When a test fails and you can’t see why, the next skill is finding out what the code is really doing, which is the subject of the Debugging piece. For Go itself, its own piece is about Go and the way it runs many things at once.
To go further with Go’s tools, the Go team’s tutorial has a short
step on adding a test, and the Go wiki has
a page on table-driven tests with more
patterns. The full reference is go help test, go help testflag and
go doc testing, all already on your disk.
The hint
Compare has a bug waiting for you. Real versions are sometimes pre-releases,
like 1.0.0-beta, and a beta comes before the release it leads up to. Don’t fix
the code. First add the row that says so to the table:
{"1.0.0-beta", "1.0.0", -1},
Before you run go test, guess what it will say. Then run it and read the failure.
Is it the failure you expected? What does it tell you about how Compare sees that
version? Only then change the code, and watch that row go green with every other
row still green beside it.
Write the test before fixing the bug. It’s the one habit from this piece that travels to every language you’ll ever use.
Related
- Rust, for errors as values, which
Compareuses to refuse bad input. - Go, the language used here, through its own concept: message passing.
- Debugging, for when a test fails and you can’t see why.
Tested with Go 1.27.4, November 2026.
The Programming Shortcut: Debugging
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about debugging: finding out what a program is actually doing.
The program is right. You are wrong.
Here is the uncomfortable truth at the bottom of every bug: your program is doing what you told it to do. It isn’t confused. It didn’t misunderstand you. It followed every instruction, in order, with perfect obedience, and the result is wrong because one of your instructions doesn’t mean what you think it means.
That’s the most useful fact in this article. It means a bug is not a mystery inside the computer. It’s a gap between two things you can look at: what you believe the program does, and what it actually does. Debugging is the work of finding the spot where those two part ways.
Most people, when a program gives the wrong answer, start fixing. They change a
< to a <=, run it again, and see if the problem goes away. Sometimes it does,
and they learn nothing. Sometimes it doesn’t, and now there are two changes to
undo. Debugging starts one step earlier. Before you change anything, you find out
what is going on.
So debugging, in this article, means finding out what a program is actually doing. Fixing is the easy part that comes afterward.
We’ll use C, because C checks almost nothing on your behalf, so the gap between belief and reality can get wide, and it has
some of the oldest and sharpest tools for looking into that gap. You don’t need
to know C to follow along. If you can read a for loop in any language, you can
read every line of code here.
If you learned lux, you may have met lux trace, which runs a program and shows
the value each line changed. A debugger is the same idea with you in charge: you
choose where the program stops and what to ask it.
Compile, run, look
This article uses Linux, because that’s where the tools here are at home. On Windows, the same steps work inside WSL (the Windows Subsystem for Linux). On a Mac, the built-in debugger is LLDB, and its GDB to LLDB command map translates everything below.
You need two programs: GCC, the GNU C compiler, and GDB, the GNU debugger. On Debian or Ubuntu, one command installs both:
sudo apt install gcc gdb
(The GDB home page has the rest.)
C is a compiled language: you don’t run the source file, you run a separate
program the compiler builds from it. So every change takes three steps. Edit the
file, compile it, run what came out. Save this as words.c:
#include <stdio.h>
int count_words(const char *text) {
int count = 1;
for (int i = 0; text[i] != '\0'; i++) {
if (text[i] == ' ') {
count++;
}
}
return count;
}
int main(void) {
printf("%d\n", count_words("a b"));
}
A string in C is an array of characters ending in a zero character, written
'\0', so the loop walks the text one character at a time until it reaches the
end. The function counts the spaces and adds one. Two words, one space between
them: two. Compile and run:
gcc -std=c23 -Wall -Wextra -g -fsanitize=address,undefined -o words words.c && ./words
That’s a long line, so here it is in pieces. -std=c23 picks the current C
standard. -Wall -Wextra turns on the compiler’s warnings, which catch a lot of
mistakes before you ever run anything. -g is the one this article leans on: it
tells the compiler to keep debugging information, a map from the machine code
back to your line numbers and variable names. Without it, a debugger can only show
you raw memory addresses. -fsanitize=address,undefined turns on two
sanitizers, extra checks built into your program that catch certain memory
mistakes the moment they happen; more on those later. -o words names the
program, and && ./words runs it if the compile worked.
The program prints:
3
Two words. It says three. Good: we have a bug, and we know how to make it happen on demand.
First, make it small
Notice what the program counts. Not “hello world” or a paragraph from a book, but
"a b", with two spaces in the middle. That’s on purpose.
The first move in any debugging session is to reproduce the bug: find an input that makes it happen every time you run the program. The second move is to make that input as small as you can. Maybe you first noticed the problem on a long sentence someone pasted in. Cut it in half and try again. If the bug is still there, cut again. If it’s gone, the cause was in the half you removed, so put that half back and cut the other one. A few rounds of halving gets you from a page of text to four characters.
This matters more than it seems. A small input means a short trip through the program, and every step you watch is a step you can understand. Nobody steps through a thousand loop iterations with a clear head.
Then, before you look at anything, say what you expect to see. Out loud, or in a comment, or on a sticky note. “The loop runs four times. The count goes up once, at the space.” A prediction turns looking into a test. When what you see doesn’t match what you said, you’ve found the gap. Without a prediction you can stare at correct-looking values all afternoon and never notice which one is wrong.
Asking with print
The oldest debugging tool is the print statement. You add a line that reports what the program is doing, run it, and read.
In C, the right place for debugging output is stderr, the standard error
stream. It’s a second output channel, separate from the normal one, so your
reports don’t mix into the program’s real output, and it’s written out
immediately rather than saved up, so you still see it if the program crashes a
moment later. fprintf(stderr, ...) is how you write to it:
#include <stdio.h>
int count_words(const char *text) {
int count = 1;
for (int i = 0; text[i] != '\0'; i++) {
fprintf(stderr, "i=%d char='%c' count=%d\n", i, text[i], count);
if (text[i] == ' ') {
count++;
}
}
return count;
}
int main(void) {
printf("%d\n", count_words("a b"));
}
Compile and run it the same way. Here’s what comes out:
i=0 char='a' count=1
i=1 char=' ' count=1
i=2 char=' ' count=2
i=3 char='b' count=3
3
Compare that with the prediction. “The count goes up once, at the space.” But
there are two spaces, at i=1 and i=2, and the count went up at both. The
function doesn’t count words. It counts spaces, and it was only right when every
gap between words happened to be one space wide.
That’s the bug found. Notice how little cleverness it took. One line of output, one prediction, one comparison.
Print statements have real strengths. They work in every language, in every environment, even on a server where you can’t run anything interactive. They leave a record you can read top to bottom.
They have one big weakness: you have to decide in advance what to ask. If the output makes you wonder about a different variable, you edit, compile and run again. For a small program, fine. For a bug that takes two minutes to reproduce, each new question costs two minutes. And afterward you have to find every print you added and take it out.
Asking with a debugger
A debugger is a program that runs your program for you, and can pause it. While it’s paused, you can look at any variable, run one line, look again, and decide what to ask next. The questions don’t have to be planned. You ask them as they occur to you, while the program waits.
Take out the fprintf line, compile again, and start GDB with the program’s name:
gdb ./words
GDB prints a little banner and gives you a (gdb) prompt. Nothing has run yet.
First, tell it where to stop. A breakpoint is a spot in your code where the
debugger will pause the program. You can name a function or a line number:
(gdb) break count_words
Breakpoint 1 at 0x11c6: file words.c, line 4.
(gdb) run
Starting program: /home/you/words
Breakpoint 1, count_words (text=0x555555556060 "a b") at words.c:4
4 int count = 1;
The program started, ran until it entered count_words, and stopped. GDB shows
you the line it’s about to run, not the one it just ran: line 4 hasn’t happened
yet. It also shows the function’s arguments, so you can see the text really is
"a b". (The long number is the text’s address in memory, which you can ignore.)
Now move forward. next runs one line and stops again:
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
(gdb) next
6 if (text[i] == ' ') {
(gdb) print text[i]
$1 = 97 'a'
print shows the value of anything you can write in C: a variable, an array
element, a little expression. A character prints as its number and its symbol, so
97 'a' is the letter a. The $1 is GDB numbering its answers so you can refer
back to them.
Typing print after every step gets old. display asks GDB to show a value
automatically every time the program stops:
(gdb) display i
1: i = 0
(gdb) display count
2: count = 1
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
1: i = 0
2: count = 1
(gdb) next
6 if (text[i] == ' ') {
1: i = 1
2: count = 1
(gdb) next
7 count++;
1: i = 1
2: count = 1
(gdb) next
5 for (int i = 0; text[i] != '\0'; i++) {
1: i = 1
2: count = 2
(gdb) next
6 if (text[i] == ' ') {
1: i = 2
2: count = 2
(gdb) next
7 count++;
1: i = 2
2: count = 2
There it is again, without editing the program: line 7 runs a second time, at
i = 2, and the count is about to reach three. You watched the belief (“one
space, one new word”) fail in real time. Pressing Enter on an empty line repeats
the last command, so stepping is mostly one key.
A few more commands cover most of what you’ll do. step is like next, but when
the line calls a function, step goes into it and next runs it in one go.
continue lets the program run until it hits another breakpoint or ends.
finish runs until the current function returns, and shows you what it returned:
(gdb) finish
Run till exit from #0 count_words (text=0x555555556060 "a b") at words.c:7
0x000055555555537b in main () at words.c:14
14 printf("%d\n", count_words("a b"));
Value returned is $2 = 3
backtrace answers “how did I get here?” by listing the chain of function calls
that led to the current line, innermost first. info locals prints every local
variable at once. quit leaves.
That’s how a debugging session goes: set a breakpoint, run, step, look. When you change the
code, you compile again and type run in the same GDB session; it notices the
new program and picks it up, and your breakpoints are still there.
Stopping when something changes
Stepping line by line is fine for four characters. Real bugs hide in loops that run thousands of times, and you don’t want to press Enter thousands of times. Two kinds of stop are smarter than a plain breakpoint.
A conditional breakpoint stops only when an expression is true. break 7 if i == 2 stops at line 7 only on the trip where i is 2, and runs straight through
the others. When you know which iteration goes wrong, this takes you there
directly.
A watchpoint doesn’t care about lines at all. watch count tells GDB to stop
whenever count changes, wherever that happens, and to show you the old value and
the new one. When the question is “who is changing this variable, and when?”, a
watchpoint answers it.
Watchpoints have one surprise. A local variable only exists while its function is running, so when the function returns, GDB deletes the watchpoint and says so. You’ll see that message in the project, and it tells you something useful there.
Where C won’t help you
In most languages you’ve used, certain mistakes stop the program at the line with
the mistake. Read past the
end of a list in Python and you get an IndexError with a line number. Java, Go
and Rust stop too. JavaScript carries on, but it hands you undefined, not some
stray number from elsewhere in memory.
C doesn’t. In C, reading or writing past the end of an array is undefined behavior, the C standard’s term for things the language makes no promises about at all. The program might crash. It might carry on with whatever happened to be in memory after the array. It might write into a neighboring variable, and the wrong value shows up ten functions later, far from the line that caused it. That’s the cruelest kind of bug, because the symptom points somewhere innocent.
Here’s a small one. The loop says <= where it means <, so it reads a fourth
score from a three-score array. Save it as main.c:
#include <stdio.h>
int main(void) {
int scores[3] = {90, 85, 77};
int total = 0;
for (int i = 0; i <= 3; i++) {
total += scores[i];
}
printf("%d\n", total);
}
Built without sanitizers, this printed 255 on my machine: the real total of 252,
plus 3 from whatever sat in memory just past the array. No error, no warning, just
a slightly wrong number. On another machine it could be any number at all.
Built with the sanitizers from the compile command above, the same program stops at the line that did it:
main.c:7:24: runtime error: index 3 out of bounds for type 'int [3]'
...
==76289==ERROR: AddressSanitizer: stack-buffer-overflow on address 0x7f880350002c
READ of size 4 at 0x7f880350002c thread T0
#0 0x5592cf976415 in main main.c:7
The AddressSanitizer checks every memory access, and the UndefinedBehaviorSanitizer checks for things like this out-of-range index. Together they give back a good part of the promise C left out, at the cost of a slower program. That’s why they’re in every compile command in this article. For more on how C lays out arrays in memory, and why nothing stops you walking off the end of one, see the C article.
One more thing C takes away: when the compiler optimizes (the -O2 flag, for
example), it rearranges and removes code, and the debugger can no longer match
machine instructions to your lines. Variables show up as <optimized out> and
next jumps around. Debug with optimization off, which is GCC’s default.
Beware of the bug that goes away when you look at it. Sooner or later you’ll
add a printf, or run under GDB, and the bug will vanish. It’s tempting to call
that fixed and leave the print in. Don’t. In C, a bug that changes when unrelated
code changes is almost always undefined behavior: something is reading memory it
shouldn’t, and your print just moved what lives there. The bug is still in the
program, waiting for a different compiler or a different day. Turn the sanitizers
on, reproduce it again, and keep looking until you can point at the line.
Project: the streak that wasn’t counted
The project is a small program with a bug in it. Your job is to find the bug with GDB before you read the answer.
streak.c takes a list of daily temperatures and reports the longest rise: the
most days in a row where each day was warmer than the one before. Get the file
from projects/debugging/streak.c, or copy it from here (the full file also ends
with a block of “Try this next…” ideas):
#include <stdio.h>
#include <stdlib.h>
int longest_rise(const int *temps, int count) {
int best = 1;
int current = 1;
for (int i = 1; i < count; i++) {
if (temps[i] > temps[i - 1]) {
current++;
} else {
if (current > best) {
best = current;
}
current = 1;
}
}
return best;
}
int main(int argc, char *argv[]) {
int count = argc - 1;
int temps[100];
if (count < 1 || count > 100) {
fprintf(stderr, "usage: %s TEMP TEMP ... (1 to 100 readings)\n", argv[0]);
return 1;
}
for (int i = 0; i < count; i++) {
temps[i] = atoi(argv[i + 1]);
}
printf("longest rise, in days: %d\n", longest_rise(temps, count));
return 0;
}
main reads the temperatures from the command line (argc counts the words you
typed, argv holds them, and atoi turns each into a number) and passes them to
longest_rise. In C, an array handed to a function arrives as a pointer, the
memory address of its first element, which is why the function also needs count
to know where the array ends; the C article explains pointers properly.
Compile it and try two inputs:
$ gcc -std=c23 -Wall -Wextra -g -fsanitize=address,undefined -o streak streak.c
$ ./streak 3 4 5 1 2
longest rise, in days: 3
$ ./streak 5 1 2 3 4
longest rise, in days: 1
The first is right: 3, 4, 5 is three days of rising. The second is wrong. 1, 2, 3,
4 rises for four days, and the program says one. You have a reproduction, and
5 1 2 3 4 is already small.
Make your prediction. best starts at 1. The rise 1, 2, 3, 4 is four days long,
so somewhere during the loop, best should change to 4. Ask GDB whether it does.
--args lets you pass the temperatures along:
$ gdb --args ./streak 5 1 2 3 4
(gdb) break longest_rise
Breakpoint 1 at 0x224b: file streak.c, line 5.
(gdb) run
Starting program: /home/you/streak 5 1 2 3 4
Breakpoint 1, longest_rise (temps=0x7ffff4c00030, count=5) at streak.c:5
5 int best = 1;
(gdb) next
6 int current = 1;
(gdb) watch best
Hardware watchpoint 2: best
(gdb) continue
Continuing.
Watchpoint 2 deleted because the program has left the block in
which its expression is valid.
0x0000555555556823 in main (argc=6, argv=0x7fffffffd7f8) at streak.c:30
30 printf("longest rise, in days: %d\n", longest_rise(temps, count));
We stepped once past line 5 so best had its starting value before we watched
it. Then the program ran the whole loop, and the watchpoint never fired. It was
deleted when longest_rise returned. That’s the answer to the question we asked:
best never changed.
So the next question is what the function knew when it gave up. Clear the old
breakpoints with delete, stop at the return on line 17 instead, and run
again, saying yes to starting over:
(gdb) delete
Delete all breakpoints, watchpoints, tracepoints, and catchpoints? (y or n) y
(gdb) break 17
Breakpoint 3 at 0x55555555642c: file streak.c, line 17.
(gdb) run
The program being debugged has been started already.
Start it from the beginning? (y or n) y
Starting program: /home/you/streak 5 1 2 3 4
Breakpoint 3, longest_rise (temps=0x7ffff4c00030, count=5) at streak.c:17
17 return best;
(gdb) info locals
best = 1
current = 4
There’s the gap.
The function counted the rise perfectly: current is 4. It just never copied
that into best. Look at where the copy happens: inside the else, which only
runs when a rise ends because the temperature fell. This rise didn’t end with a
fall. It ended with the list. The loop finished, and nobody checked the last
streak.
That’s why 3 4 5 1 2 worked: its longest rise ended with a drop to 1, which
triggered the copy. The bug only shows when the longest rise is the last thing in
the list. Plenty of hand-picked test inputs would miss it.
Now you can fix it, and the fix follows from what you saw. The comparison
shouldn’t wait for the rise to end. Move it out of the else, so it runs after
every day:
if (temps[i] > temps[i - 1]) {
current++;
} else {
current = 1;
}
if (current > best) {
best = current;
}
Compile, and run both inputs again:
$ ./streak 5 1 2 3 4
longest rise, in days: 4
$ ./streak 3 4 5 1 2
longest rise, in days: 3
Then run it under GDB once more with watch best, and watch it climb from 1 to 2
to 3 to 4. Seeing the fixed program behave the way you predicted is the other half
of debugging: the gap is closed.
What’s left out
GDB can open a core dump, the snapshot of memory a crashed
program leaves behind, and show you the moment of the crash after the fact. It can
attach to a program that’s already running. It has a text interface that shows
your source code above the prompt (gdb -tui). Programs that do several things at
once have their own debugging problems, and GDB has commands for each thread.
Memory checkers like Valgrind, logging libraries, and the debuggers built into
editors all do versions of what you did here. If you use version control, git bisect applies the halving trick to your history, to find the change that
introduced a bug; the version control piece covers git.
When you’ve found a bug, a good habit is to write a small test that fails because of it, before you fix it, so you’ll hear about it if it ever comes back. The testing piece is about that.
For going further with GDB itself, the manual is Debugging with GDB, written by the people who make it. Its chapters on stopping and continuing, and on examining data, are the ones to read next.
Your turn
Pick a program you think you understand. One you wrote last month, or words.c,
or streak.c after the fix. Start it in GDB, type break main and run, and
then step through it, one line at a time, into every function it calls.
Before each step, say what the next line will do and what the values will be.
Then press Enter and see. Bring one question to it: where does my prediction
first go wrong? Expect a surprise, sooner than you’d think, in code you would
have sworn you knew. When you do, type help and look for the
command that would have shown it to you sooner.
Related
- C: arrays, pointers and memory, and why reading past the end of an array is allowed to happen
- Testing: turning a bug you’ve found into a check that keeps it from coming back
- Version control: saving and comparing your project’s history, the history
git bisectsearches
Tested with GCC 14.2 and GDB 16.3, November 2026.
The Programming Shortcut: Version control
Part of The Programming Shortcut, a series that teaches one programming idea per article to people who already program. This one is about version control: saving, comparing and undoing your work.
You already do version control, badly
Somewhere on your computer there is a file called report_final.docx. Next to it is
report_final_v2.docx, and next to that, if things went the way they usually go,
report_final_v2_REALLY.docx.
You’ve done the programming version too. You copied main.py to main_old.py
before trying something risky. You commented out a block of code instead of
deleting it, “just in case.” You pressed undo forty times in a row, hoping to land
on the version that worked an hour ago, and then the editor crashed and took the
undo history with it.
Every one of those is version control. You were saving versions of your work so you could compare them and go back. You just did it by hand, with filenames and hope.
A version control system is a program that does this for you, properly. It keeps every version of your project you ask it to keep, it labels each one with who made it, when and why, and it can tell you what changed between any two of them, down to the line. It can also take you back, and it does that without throwing the present away.
That’s the concept this piece teaches, in three verbs: saving, comparing and undoing. Every version control system you’ll ever meet does those three things, and once you can see them in one, you’ll recognize them in the rest.
The one we’ll use is git. It was born in 2005, when the people building the
Linux kernel, led by Linus Torvalds, needed a tool that could keep thousands of
programmers from trampling each other’s work. That sounds like a tool for someone
else. But the same tool works for one person, in one folder, on
one laptop, with no server, no account and no internet connection. Everything in
this piece happens on your own machine.
One folder and one hidden drawer
First, check that git is there. Open a terminal and type:
$ git --version
git version 2.47.3
Any recent version is fine. If the command isn’t found, install git from
git-scm.com/install; on Debian or Ubuntu, that’s
sudo apt install git. On Windows, the installer gives you Git Bash, a terminal
where every command in this piece works as written.
Git signs your name on everything you save, so it needs to know your name once. These two lines go in a settings file in your home folder, and you never type them again:
$ git config --global user.name "Your Name"
$ git config --global user.email "you@example.com"
Now make a folder to play in, and turn it into a repository. A repository (or repo) is a folder whose history git keeps:
$ mkdir ideas
$ cd ideas
$ git init
Initialized empty Git repository in /home/you/ideas/.git/
Git may also print a few lines of hints about the name master. You can ignore
them for this piece.
That .git folder is the hidden drawer. It’s where every saved version of your
project will live. Your own files stay where they are, and look like normal files,
because they are. Delete the .git folder and you’re back to an ordinary folder
with no history at all. Your history lives nowhere else.
Make a file called ideas.txt in any editor, with three lines:
Things I could build:
- a dice roller
- a to-do list
Then ask git what it sees:
$ git status
On branch master
No commits yet
Untracked files:
(use "git add <file>..." to include in what will be committed)
ideas.txt
Untracked means git can see the file but hasn’t been asked to look after it. Two
commands change that. git add puts the file into the next save, and git commit
makes the save:
$ git add ideas.txt
$ git commit -m "Start a list of ideas"
[master (root-commit) 0f5e4dc] Start a list of ideas
1 file changed, 3 insertions(+)
create mode 100644 ideas.txt
That’s your first commit: one saved version of the project, with a message
saying what it was for. The -m gives the message right there on the command
line. Leave it off, and git opens an editor for you to write one.
Now change something. Edit the file: change the to-do list line and add a fourth idea.
Things I could build:
- a dice roller
- a to-do list that nags
- a word counter
Before you save it into history, look at what you did:
$ git diff
diff --git a/ideas.txt b/ideas.txt
index 5e4b096..54d89b6 100644
--- a/ideas.txt
+++ b/ideas.txt
@@ -1,3 +1,4 @@
Things I could build:
- a dice roller
-- a to-do list
+- a to-do list that nags
+- a word counter
A line starting with - was there before and isn’t now. A line starting with +
is new. A line starting with a space didn’t change; git shows a few of those as
context, so you can see where you are. Changing a line shows up as one line out
and one line in. The @@ -1,3 +1,4 @@ line says where you are in the file: three
lines starting at line 1 before, four lines starting at line 1 after.
Happy with it? Save it:
$ git add ideas.txt
$ git commit -m "Add a word counter"
[master b676d88] Add a word counter
1 file changed, 2 insertions(+), 1 deletion(-)
Everything that follows comes back to those steps: edit, look with git diff,
then git add and git commit. The editor’s save button saves your file. A commit
saves a version of your project. You’ll press the first one constantly, and the
second one whenever you reach a point you’d like to be able to come back to.
A commit is a photograph of everything
Ask git for its history:
$ git log
commit b676d881b8fec963a723263a376ebd11eb015a80
Author: Your Name <you@example.com>
Date: Sun Nov 22 15:34:02 2026 -0600
Add a word counter
commit 0f5e4dc48c7c4c4795fd4c5dc354b6e11575d09a
Author: Your Name <you@example.com>
Date: Sun Nov 22 15:34:02 2026 -0600
Start a list of ideas
Newest first. Each commit carries four things, and between them they are the concept.
A snapshot. A commit isn’t a list of changes. It’s a complete picture of every file git is looking after, as it was at that moment. If your project had fifty files, each commit holds all fifty. (Git is clever about not storing the same file twice, so this costs far less disk than it sounds.) The diffs you just saw are something git works out by comparing two snapshots, when you ask.
A message, an author and a time. Who saved this, when, and why. The “why” is the one only you can supply, and it’s the one future you will want most.
A parent. Every commit except the first remembers the commit that came before
it. That’s how a pile of snapshots becomes a history: each one points back to its
parent, and the chain runs all the way to the first commit, which has no parent at
all. Git calls that one the root commit, which is why the first git commit
printed root-commit.
A name. That long string of letters and numbers is the commit’s hash: a
fingerprint git computes from everything in the commit, including the snapshot, the
message, the author, the time and the parent. Change one character of any of them
and you get a different fingerprint. You’ll rarely type all forty characters.
The first seven or so are enough, and git log --oneline shows only those:
$ git log --oneline
b676d88 Add a word counter
0f5e4dc Start a list of ideas
Your hashes won’t match mine, because yours include your name and the moment you committed. Wherever this piece uses a hash, use one from your own log.
Because the parent is part of what gets fingerprinted, a hash names the commit and everything before it. Change anything in an old commit and every commit after it gets a new name too. That’s how git can promise that the history you’re looking at is the history that happened.
Two more names come up constantly. HEAD means “the commit you’re on right now,”
which is usually the newest one. HEAD~1 means one step back from there, HEAD~2
two steps back, and so on.
Three places your work can be
There’s one wrinkle in those steps, and it’s git add. Why not commit
straight away?
Because git keeps your work in three places, and it helps to picture them:
your folder the staging area the history
(what you edit) --> (the next snapshot) --> (every commit)
git add git commit
The staging area (git also calls it the index) is the next snapshot, still
being packed. git add copies a file’s current state into it. git commit takes
whatever’s packed and makes it permanent. That gap lets you choose. If you fixed a
bug and also tidied up some spacing, you can add and commit the fix on its own, then
the tidying, and each commit says one thing.
git diff with nothing after it compares your folder with the staging area. So
once you git add a file, plain git diff goes quiet. To see what’s packed and
about to be committed, ask for the staged diff:
$ git diff --staged
Not every version control system has a staging area. Some commit everything that changed, every time. But nearly all of them have snapshots, messages and parents, and when you meet a new one, those are the three things to look for. Even the version history in a shared online document is the same idea in disguise: snapshots, each with an author and a time, in a line that points back to the start.
Comparing: what changed, and when?
A history you can’t compare is just a pile of old copies. The report_final_v2
approach fails here: two files, and no way to see what’s different between them
except reading both.
You’ve already used the most common comparison, git diff, for “what have I done
since my last save?” The same command compares any two commits. Name them, older
first:
$ git diff HEAD~1 HEAD
That shows what the most recent commit changed. You can use hashes in place of
HEAD~1 and HEAD, from any distance apart, and git will show everything that
changed between those two snapshots, however many commits lie in between.
To see a single commit, with its message and its changes together, use git show:
$ git show b676d88
And to read the history as a story, every commit with its changes underneath, add
-p (for patch, an old name for a diff) to git log:
$ git log -p
That output is usually longer than one screen, so git shows it a page at a time.
Press the space bar for the next page and q to quit.
Sometimes you don’t want a comparison at all, just a look at how a file used to
be. git show can do that too, with a colon between the commit and the file:
$ git show HEAD~1:ideas.txt
Things I could build:
- a dice roller
- a to-do list
Nothing in your folder changed. You just looked into the drawer.
Here’s the habit that makes all of this pay off: commit small, and say why. A commit that does one thing has a diff you can read in ten seconds. A commit called “stuff” that touched thirty files has a diff nobody will ever read, including you.
Undoing without forgetting
Undo in an editor walks backwards and forgets. Press it ten times, type one character, and those ten steps are gone for good. Version control undoes things a different way, and the difference is the most useful idea in this piece.
There are three kinds of mistake, and they get undone at three different places.
An edit you haven’t committed yet. You changed a file, it went badly, and you
want the last saved version back. git restore copies it from the staging area
over your file:
$ echo "- delete everything" >> ideas.txt
$ git restore ideas.txt
Your bad edit is gone, and the file matches your last commit again. If you’d
already run git add on the bad edit, take it back out of the staging area first
with git restore --staged ideas.txt, then restore the file.
A file you want from further back. Maybe the version you want is one commit
back. Tell git restore where to get it from:
$ git restore --source=HEAD~1 ideas.txt
Now your folder holds the older version of that one file, and git diff will show
you the difference from where you were. If you like it, add and commit it like any
other change. If you don’t, git restore ideas.txt puts you back. Do that now, because the
next command wants a folder with no uncommitted changes.
A commit you wish you hadn’t made. This is where version control is cleverest.
You might expect it to delete the bad commit. It doesn’t. git revert works out
the opposite of that commit’s changes, applies them, and saves the result as a
new commit:
$ git revert --no-edit HEAD
[master 1972de8] Revert "Add a word counter"
Date: Sun Nov 22 15:34:14 2026 -0600
1 file changed, 1 insertion(+), 2 deletions(-)
$ git log --oneline
1972de8 Revert "Add a word counter"
b676d88 Add a word counter
0f5e4dc Start a list of ideas
(Without --no-edit, git opens an editor so you can write your own message.)
Look at that log. The mistake is still there. So is the undo, with a name and a date. Your file is back the way it was, and the history has grown by one.
Banks have kept books this way for centuries. When an accountant finds a wrong entry in a ledger, they don’t scratch it out. They add a new entry that cancels it. The books always add up, and you can always see what happened and when it was put right. Version control works on the same rule: history only grows. Undoing is something you do, so it becomes part of the record.
That’s the answer to report_final_v2_REALLY. You never needed a copy of every
version with a cleverer name. You needed one file, a record of every version it
has been, and a way to say “put this back” that doesn’t destroy the evidence.
Saved isn’t committed
Most of the software you use makes a simple promise: when you press save, your work is safe. Git makes a narrower one. It protects what you have committed, and nothing else.
Edits you haven’t committed are just files in a folder. git restore overwrites
them without asking, and nothing in the drawer remembers them, because they never
went in. That’s why the habit matters: commit early, commit often, and the worst a
mistake can cost you is the work since your last commit.
And the ledger has an eraser, if you go looking for it. Git has commands that rewrite history: that move you back to an earlier commit as if later ones never happened, rewrite the last commit, or replace a shared history with yours. They exist for good reasons, mostly to tidy up commits before anyone else sees them. But they give up the promise that history only grows.
Beware of
git reset --hard. It turns up in a lot of answers online, because it’s a quick way to make a messy folder match the last commit. It does that by throwing away every uncommitted change, in every file, at once, with no confirmation and no undo. My advice: leave it alone until you can say, without looking it up, what it will destroy. To throw away an edit,git restorethe one file you meant. To undo a commit,git revertit. Both take longer to type, and both only do what you asked.
Who put twenty eggs in the pancakes?
The project is a kitchen with a history, and a mystery in it.
It’s one script, story.sh, in projects/version-control/. It makes a throwaway
repository in a fresh temporary folder (your own folders aren’t touched) and
fills it with five commits of a pancake recipe, written by someone called Sam. Here
it is in full, apart from the “Try this next…” hints at the end of the file:
set -e
repo=$(mktemp -d)
cd "$repo"
git init --quiet --initial-branch=main
git config user.name "Sam Baker"
git config user.email "sam@example.com"
save() {
git add pancakes.txt
GIT_AUTHOR_DATE="$1" GIT_COMMITTER_DATE="$1" git commit --quiet -m "$2"
}
cat > pancakes.txt <<'RECIPE'
Pancakes
1 cup flour
1 tablespoon sugar
2 teaspoons baking powder
a pinch of salt
1 cup milk
2 eggs
2 tablespoons melted butter
RECIPE
save "2026-11-02 08:00 +0000" "Start a pancake recipe"
cat >> pancakes.txt <<'RECIPE'
Mix the dry things.
Beat the milk, eggs and butter, and pour them in.
Stir until just combined. Lumps are fine.
Cook on a hot pan until bubbles pop, then flip.
RECIPE
save "2026-11-03 08:00 +0000" "Add the method"
sed -i.bak -e 's/^2 eggs$/20 eggs/' -e 's/^Mix the dry things\.$/Whisk the dry ingredients together./' pancakes.txt
rm pancakes.txt.bak
save "2026-11-05 08:00 +0000" "Tidy up wording"
cat >> pancakes.txt <<'RECIPE'
Serve with butter and maple syrup.
RECIPE
save "2026-11-08 08:00 +0000" "Add a serving suggestion"
sed -i.bak -e 's/^Pancakes$/Pancakes (serves 4)/' pancakes.txt
rm pancakes.txt.bak
save "2026-11-09 08:00 +0000" "Say how many it serves"
echo "A kitchen with some history is ready. Go there with:"
echo
echo " cd $repo"
The git config lines without --global set Sam’s name for this one repository
only, so your own settings stay as they are. Run the script, then go where it
tells you:
$ bash story.sh
A kitchen with some history is ready. Go there with:
cd /tmp/tmp.iRfmAG0r3R
$ cd /tmp/tmp.iRfmAG0r3R
Your folder name will be different. Look at the recipe:
$ cat pancakes.txt
Twenty eggs. Something went wrong, and you weren’t there. Start with the history:
$ git log --oneline
b8cdae8 Say how many it serves
6a6a0ff Add a serving suggestion
351a59c Tidy up wording
f4d546c Add the method
37907a1 Start a pancake recipe
None of those messages says “eggs.” That’s realistic. Nobody writes “made the recipe wrong” in a commit message. So read the changes instead of the labels:
$ git log -p
Page down until you find it. (While git is showing a page, pressing / and typing
eggs searches for it.) Here’s the commit you’re looking for:
commit 351a59cd6251501e855780cf053050543c641886
Author: Sam Baker <sam@example.com>
Date: Thu Nov 5 08:00:00 2026 +0000
Tidy up wording
diff --git a/pancakes.txt b/pancakes.txt
index f116744..d44bc5f 100644
--- a/pancakes.txt
+++ b/pancakes.txt
@@ -5,10 +5,10 @@ Pancakes
2 teaspoons baking powder
a pinch of salt
1 cup milk
-2 eggs
+20 eggs
2 tablespoons melted butter
-Mix the dry things.
+Whisk the dry ingredients together.
Beat the milk, eggs and butter, and pour them in.
Stir until just combined. Lumps are fine.
Cook on a hot pan until bubbles pop, then flip.
“Tidy up wording,” it says, and it slipped an extra zero onto the eggs. It also made a change that was a good idea: whisk is better than mix. Keep that in mind.
Undo the commit. Use the hash from your own log:
$ git revert --no-edit 351a59c
Auto-merging pancakes.txt
[main b73041a] Revert "Tidy up wording"
Date: Sun Nov 22 15:34:30 2026 -0600
1 file changed, 2 insertions(+), 2 deletions(-)
Two commits came after the bad one, and git kept both: the recipe still serves 4, and the maple syrup is still there. Revert takes out one commit’s changes and leaves everything later alone. Check what your new commit did:
$ git diff HEAD~1 HEAD
Two eggs again. But whisk went back to mix as well, because a revert undoes a whole commit, good changes and bad. That’s the price of a commit that did two things, and it’s the clearest argument for small commits you’ll ever get from a pancake.
So finish the job the ordinary way. Open pancakes.txt in your editor, change “Mix
the dry things.” back to “Whisk the dry ingredients together.”, and save the file.
Then look, and commit:
$ git diff
$ git add pancakes.txt
$ git commit -m "Whisk, don't mix"
Each of those prints something of its own. Then the log:
$ git log --oneline
0e2d15f Whisk, don't mix
b73041a Revert "Tidy up wording"
b8cdae8 Say how many it serves
6a6a0ff Add a serving suggestion
351a59c Tidy up wording
f4d546c Add the method
37907a1 Start a pancake recipe
Your top two hashes will differ from these, because they include the time you made them. Sam’s five should match, because the script fixes everything those five fingerprints are made from: the recipe, the messages, Sam’s name and the dates.
Read that log from the bottom up and it tells the story: the recipe, the slip, the fix, and the good idea put back. Nothing was erased. Anyone who reads it later can see what happened, in what order, and why.
When you’re done, the temporary folder can go: rm -rf the path the script
printed, or leave it for your system to clear away. The story.sh in the project
folder ends with more things to try in that kitchen before you do.
What I left out
This piece left out most of git, and it’s meant to.
There are no branches here: lines of history that split off so you can try
something without disturbing the main line, and merging, which brings them back
together. There are no remotes, the copies of a repository on another machine or
a service like GitHub, with the clone, push and pull that move commits between
them. That’s how teams share history, and it’s built on top of everything above. I
also skipped rewriting history (rebase, amend), setting work aside for later
(stash), telling git to ignore files (.gitignore), and what’s inside the .git
folder.
Every one of those is built from the three things you now have: snapshots with parents, comparison between snapshots, and undo by adding a new snapshot. A branch is a name pointing at a commit. A merge is a commit with two parents.
When you want the rest, the official book is free: Pro Git,
by Scott Chacon and Ben Straub. Git also ships with a short guide to the commands
people use every day: run git help everyday.
Your own history
Find a project you’ve been working on for a while. If it isn’t in git yet, go into
its folder and run git init, then git add . and git commit -m "Where things stand", and come back in a week.
If it is in git already, run:
$ git log -p
and pick one line of code you wrote. Bring this question: when did this line become what it is, and what did I think I was doing? The answer is in there, with a date on it.
Related
- Testing: commit tests with the code they check, and the history can tell you which commit made a test start failing.
- Debugging: finding out what a program is doing. Knowing when a bug arrived, and which diff brought it, often finds it faster than any debugger.
Tested with git 2.47, November 2026.