Chapter 4: Structuring programs, from REPL to webpage
The chapter introduces a word ladder game that will be built first as a REPL and then as a web application.
After this chapter you will be able to
- Word ladder game rules. Describe a word ladder as a series of same-length words in which each word differs from the previous one by one letter, and state the challenge of extending a ladder from a randomized starting word.
- Dictionary roles in word ladders. Explain why the word ladder game needs a dictionary: it determines whether words are valid and supplies words that can start a ladder.
- Compile-time static data validation. Explain why loading unchanging files at startup can be brittle and how comptime lets a program load, parse, verify, and store that data during compilation instead.
- Deterministic comptime execution. Explain why comptime code cannot use nondeterministic behavior such as operating-system interaction or randomness, and where such tasks can go instead.
- Comptime branch quota. Describe why comptime expressions have a backwards-branch limit and what to do when the compiler reports that the limit has been reached.
- Compile-time wordlist parsing. Trace how the newline-separated wordlist is counted and parsed into an array whose size is determined at comptime, including the check that words have four characters.
- Executing the embedded parser. Describe how the section brings the wordlist text into compile-time parsing, and what labeled blocks and the branch quota contribute.
- Lazy comptime evaluation. Explain why unused code may escape semantic checking and how a known-at-comptime target OS makes that behavior useful.
- Word ladder interaction loop. Describe how the game accepts player text and displays feedback in a loop, and explain why typing “end” stops the game.
- Delimited input and buffer slice. Explain how the section reads one line of player input using a newline delimiter and what takeDelimiter returns.
- Distinct word validation errors. Explain how the word-validation function distinguishes invalid inputs so the program can give intelligible feedback. Describe its stated contract: it checks a player’s input against the previous word, returns a [4]u8 for a valid four-letter word, or returns an error for an invalid one.
- Validation and interface separation. Justify returning validation errors instead of printing messages inside the validation function. Explain how this separation of concerns keeps the code less tied to the console and easier to reuse in another interface.
- Random starting word selection. Explain how the game chooses a starting word using a seeded std.Random.DefaultPrng through the std.Random interface, and distinguish the seed's entropy source from the pseudo-random generator.
- Ladder history with ArrayList. Describe how std.ArrayList holds previous ladder words and what its allocator and items field are used for.
- Validation messages through switch. Explain how a switch expression selects a message for invalid input and what the missing else clause indicates in the example.
- Browser access for the game. Justify choosing a web application for Wilda’s word ladder game rather than asking her to use a command line or building separate native applications.
- IP TCP HTTP layers. Describe how HTTP relies on TCP, which relies on IP, and state the role the section assigns to each layer.
- Zig HTTP library tradeoff. Explain why the section characterizes Zig’s web support as minimalistic and how its HTTP library relates to the operating system’s TCP support.
- TCP server interaction loop. Trace the basic work of a TCP server: ask the OS to listen on an address and port, accept connections, then read from and respond to clients. Explain that Zig’s std.Io provides cross-platform abstractions for this work.
- Network stream echo server. Describe how the echo server treats a TCP connection as a stream, reads lines, and sends them back, much like a REPL using a network connection instead of a terminal.
- HTTP on a TCP server. Explain that HTTP messages travel over TCP, so adding HTTP to the existing Zig TCP server means replacing its communication loop with one that parses requests and sends responses.
- Resource requests and methods. Describe HTTP’s resource-oriented view and distinguish the intent illustrated by GET and POST requests.
- Response status and content. Explain how a response reports the outcome of a request and what its status code, headers, and body can convey, using the section’s examples.
- HTTP request outcomes. Describe the server’s expected POST request and successful response, and explain what happens when a GET request or an oversized body is sent instead.
- Error-only deferred response. Explain when errdefer runs, why it is used for a 500 response here, and its stated limitation.
- Word ladder endpoint design. Explain how the game's required functions determine its three HTTP endpoints and why each uses its stated method and route.
- Modular validation over HTTP. Describe how existing word ladder validation becomes a web response, including the meanings of the success and error responses.
- Upfront work and flexibility. Explain the tradeoff the author highlights: putting work into a Zig project up front can make it easier to maintain, extend, or repurpose later.
What it builds on
- Do it at comptime (chapter 1) · The earlier introduction to comptime.
- Arrays (chapter 2) · The earlier introduction to arrays.
- Writer, meet reader (chapter 3) · Prior use of readers and writers.
- Errors, catch and try (chapter 3) · Prior use of Zig errors and error unions.
- The interface pattern (chapter 3) · The interface pattern used by allocators, writers, and readers.
- Allocating with Allocators (chapter 3) · The role of allocators in obtaining memory.
- Defer to better resource management (chapter 3) · The earlier introduction to defer
Section by section
Introduction
The chapter introduces a word ladder game that will be built first as a REPL and then as a web application.
- Word ladder game rules: Describe a word ladder as a series of same-length words in which each word differs from the previous one by one letter, and state the challenge of extending a ladder from a randomized starting word.
Why it matters: These rules define the game the chapter builds.
Key terms: word ladder, randomized starting word
4.1 Climbing the ladder
Introduces the dictionary’s two roles in the word ladder game: checking words and supplying starting words.
- Dictionary roles in word ladders: Explain why the word ladder game needs a dictionary: it determines whether words are valid and supplies words that can start a ladder.
Why it matters: These two uses explain why the game needs a dictionary at all.
Key terms: dictionary, word validity, start the ladder
4.1.1 Thinking in comptime
This section explains how comptime can move checks for unchanging data from program startup to compilation, then outlines how to prepare a word ladder dictionary.
- Compile-time static data validation: Explain why loading unchanging files at startup can be brittle and how comptime lets a program load, parse, verify, and store that data during compilation instead.
Why it matters: It explains why this program prepares its fixed data before runtime instead of loading it on every run. - Word dictionary array preparation: Describe the stated steps for preparing the word ladder dictionary: load the four-character words, count them to size an array of four-character strings, and copy them into that array.
Why it matters: Counting the words explains how the section plans to represent the dictionary as an array.
Key terms: comptime, compilation, unchanging data, word ladder dictionary, four-character words, array of four-character strings
4.1.2 Comptime caveats
This section explains why Zig restricts comptime code and how to respond when compilation reaches its evaluation limit.
- Deterministic comptime execution: Explain why comptime code cannot use nondeterministic behavior such as operating-system interaction or randomness, and where such tasks can go instead.
Why it matters: This distinction helps you choose between comptime and the build system when a task needs outside information. - Comptime branch quota: Describe why comptime expressions have a backwards-branch limit and what to do when the compiler reports that the limit has been reached.
Why it matters: The quota prevents a compile-time mistake from consuming excessive build time without ruling out legitimate work.
Key terms: comptime, build hermeticity, build system, backwards branches, @setEvalBranchQuota, comptime expressions
4.1.3 Executing our plan
This section builds a compile-time wordlist parser and explains the comptime features used to run and check it.
- Comptime generic type parameters: Explain how a comptime type parameter lets one function work with multiple types, and why a call is valid only when the function body works for the supplied type.
Why it matters: This explains why a generic function can accept several numeric types without accepting an invalid operation such as adding booleans. - Compile-time wordlist parsing: Trace how the newline-separated wordlist is counted and parsed into an array whose size is determined at comptime, including the check that words have four characters.
Why it matters: The result is type-safe values made from raw text before the program runs. - Memoized comptime function calls: Explain why calling countWordlist twice with the same input need not repeat the computation.
Why it matters: It explains why using the word count in more than one place does not necessarily duplicate compile-time work. - Executing the embedded parser: Describe how the section brings the wordlist text into compile-time parsing, and what labeled blocks and the branch quota contribute.
Why it matters: These pieces let the parser operate on the actual file as part of compilation. - Compile-time logging checks: Explain how the section checks the parsed words with @compileLog and what happens when that logging remains in the code.
Why it matters: It provides a way to inspect compile-time results without accidentally shipping the logging statement. - Lazy comptime evaluation: Explain why unused code may escape semantic checking and how a known-at-comptime target OS makes that behavior useful.
Why it matters: Lazy evaluation both explains the need to reference the parsed result during checking and permits cross-platform code to leave irrelevant branches out.
Key terms: comptime type parameter, generic function, duck typed, wordlist, std.mem.tokenizeScalar, countWordlist, comptime, @compileError, comptime memoization, side effects
4.1.4 Talk to me
This section explains how the word-ladder game can read player input, display feedback, and let the player end the interaction.
- Word ladder interaction loop: Describe how the game accepts player text and displays feedback in a loop, and explain why typing “end” stops the game.
Why it matters: It gives players a way to finish when they cannot think of another word. - Delimited input and buffer slice: Explain how the section reads one line of player input using a newline delimiter and what takeDelimiter returns.
Why it matters: It connects line-oriented console input to Zig’s reader interface and explains where the resulting text resides. - Simple REPL foundation: Explain why the section treats a simple read-and-write loop as useful beyond this game.
Why it matters: A modest console loop can be a useful starting point for more ambitious tools.
Key terms: word ladder, end, stdin, stdout, delimiter, takeDelimiter, slice, reader’s internal buffer, REPL, console applications
4.1.5 Core logic
The section uses word-ladder input validation to show how distinct errors can support useful feedback while keeping validation separate from the console interface.
- Distinct word validation errors: Explain how the word-validation function distinguishes invalid inputs so the program can give intelligible feedback. Describe its stated contract: it checks a player’s input against the previous word, returns a [4]u8 for a valid four-letter word, or returns an error for an invalid one.
Why it matters: Distinguishing failures lets the program give players feedback they can act on. - Validation and interface separation: Justify returning validation errors instead of printing messages inside the validation function. Explain how this separation of concerns keeps the code less tied to the console and easier to reuse in another interface.
Why it matters: Keeping validation independent of its interface makes the same logic easier to use beyond a console game.
Key terms: error set, error union, [4]u8, word validation, separation of concerns, console environment
4.1.6 Check it
The section finishes the terminal word-ladder game by choosing a random starting word, tracking ladder words, and turning validation errors into useful messages.
- Random starting word selection: Explain how the game chooses a starting word using a seeded std.Random.DefaultPrng through the std.Random interface, and distinguish the seed's entropy source from the pseudo-random generator.
Why it matters: This explains where the game's starting word comes from without confusing OS entropy with the generator that uses the seed. - Ladder history with ArrayList: Describe how std.ArrayList holds previous ladder words and what its allocator and items field are used for.
Why it matters: Tracking prior words lets the program retain the ladder as the player builds it. - Managed and unmanaged allocator ownership: Distinguish managed and unmanaged standard-library data structures by where their allocator is kept, and explain the author's reason for recommending unmanaged variants.
Why it matters: The distinction clarifies who is responsible for keeping an allocator available and why the author prefers one variant. - Validation messages through switch: Explain how a switch expression selects a message for invalid input and what the missing else clause indicates in the example.
Why it matters: Mapping validation errors to messages makes the terminal game give useful feedback when input is invalid.
Key terms: std.Random, std.Random.DefaultPrng, seed, entropy source, std.ArrayList, allocator, items, managed, unmanaged, switch expression
4.2 Wilda’s want for words
This section explains why a browser is a practical way to make the Zig word ladder game accessible to a non-technical player across devices.
- Browser access for the game: Justify choosing a web application for Wilda’s word ladder game rather than asking her to use a command line or building separate native applications.
Why it matters: The browser makes the game easier to share with someone who wants to play on different devices without using developer tools.
Key terms: browser, web applications, Zig’s standard library, command line, native applications
4.2.1 Connecting the web
This section introduces the protocol layers beneath the web and explains why Zig’s minimal HTTP library leaves programmers close to the flow of data.
- Protocol message components: Explain that a network protocol specifies a message format containing a payload for the receiver and metadata that helps systems handle the message.
Why it matters: This gives you a way to think about the data moving through each network layer. - IP TCP HTTP layers: Describe how HTTP relies on TCP, which relies on IP, and state the role the section assigns to each layer.
Why it matters: The layers clarify which networking work is already provided and what HTTP adds. - Zig HTTP library tradeoff: Explain why the section characterizes Zig’s web support as minimalistic and how its HTTP library relates to the operating system’s TCP support.
Why it matters: It sets expectations for why building web functionality in Zig involves visible design choices rather than a ready-made framework.
Key terms: protocol, message format, payload, metadata, network layers, IP, TCP, HTTP, hypertext semantics, batteries-included web framework
4.2.2 A poor conversationalist
The section explains how a TCP echo server listens for connections, uses an address and port, and reads and responds over a network stream.
- TCP server interaction loop: Trace the basic work of a TCP server: ask the OS to listen on an address and port, accept connections, then read from and respond to clients. Explain that Zig’s std.Io provides cross-platform abstractions for this work.
Why it matters: This sequence is the foundation for the HTTP server built next. - Ports and network traffic: Explain why a server listens on an address and port, focusing on how ports distinguish traffic intended for different programs.
Why it matters: The port explains how traffic reaches the intended service at a network address. - Network interfaces and loopback: Distinguish listening on a particular network interface, on 0.0.0.0, and on the loopback address used for local development.
Why it matters: Choosing the listening address determines which network interfaces can reach the development server. - Network stream echo server: Describe how the echo server treats a TCP connection as a stream, reads lines, and sends them back, much like a REPL using a network connection instead of a terminal.
Why it matters: The echo server makes the server’s read-and-respond loop concrete before HTTP is added.
Key terms: TCP server, std.Io, listen, accept, address, port, port 80, network interfaces, 0.0.0.0, loopback device
4.2.3 How do I HTTP?
The section explains how HTTP builds on a TCP server and how requests and responses express what clients want and what happened.
- HTTP on a TCP server: Explain that HTTP messages travel over TCP, so adding HTTP to the existing Zig TCP server means replacing its communication loop with one that parses requests and sends responses.
Why it matters: This connects the TCP server already built to the HTTP server the chapter is developing. - Resource requests and methods: Describe HTTP’s resource-oriented view and distinguish the intent illustrated by GET and POST requests.
Why it matters: Thinking of requests as intentions toward resources makes HTTP exchanges easier to interpret. - Response status and content: Explain how a response reports the outcome of a request and what its status code, headers, and body can convey, using the section’s examples.
Why it matters: The status and body let a client tell whether its request succeeded and what, if anything, the server returned.
Key terms: HTTP, TCP connection, std.http, std.net TCP server, request, response, resources, GET, POST, status code
4.2.4 The HTTP cherry on top
The section shows how the echo server handles HTTP requests and errors, then checks those behaviors with curl.
- HTTP request outcomes: Describe the server’s expected POST request and successful response, and explain what happens when a GET request or an oversized body is sent instead.
Why it matters: These outcomes make the server’s intended behavior and error cases observable. - Error-only deferred response: Explain when errdefer runs, why it is used for a 500 response here, and its stated limitation.
Why it matters: The distinction explains both the server’s error response and the limit of that response path. - Separated behavior and error logging: Explain why the server logic is wrapped in a function and what the section observes after testing error cases.
Why it matters: Separating the concerns keeps error reporting distinct from the server’s behavior.
Key terms: POST, GET, 200, 400 (Bad Request), request buffer, errdefer, 500 (Internal Server Error), catch and log, separating different concerns
4.2.5 Modularity makes it easy
The section maps the modular word ladder game onto HTTP endpoints and explains how to make the resulting website available locally and on a shared network.
- Word ladder endpoint design: Explain how the game's required functions determine its three HTTP endpoints and why each uses its stated method and route.
Why it matters: The endpoints give the browser a way to access each part of the game. - Modular validation over HTTP: Describe how existing word ladder validation becomes a web response, including the meanings of the success and error responses.
Why it matters: Keeping validation separate lets the web server reuse the game's logic rather than reinvent it. - Local and subnet access: Distinguish opening the game locally in a browser from making it reachable by other devices on the same router's subnet.
Why it matters: This distinction lets someone else on the local network try the game.
Key terms: interface, endpoint, GET, POST, route, word ladder validation, modular, HTTP response, 200, 400
4.3 Next steps
This section draws out the chapter’s takeaway that upfront work in Zig can make a project easier to maintain, extend, and repurpose, then suggests ways to experiment with the word game.
- Upfront work and flexibility: Explain the tradeoff the author highlights: putting work into a Zig project up front can make it easier to maintain, extend, or repurpose later.
Why it matters: It explains why the chapter invested in a structure that can support further changes.
Key terms: Zig’s ethos, maintain, extend, repurpose
4.4 Summary
Concepts explained in this chapter
- iteratorThe iterator pattern provides an abstraction for accessing elements sequentially without exposing their underlying representation.
- @compileError@compileError is a Zig compile-time builtin that emits a compilation error with a specified message.
- genericsA generic is a parameterized program construct that can be instantiated for different types or values.
- lazy evaluationLazy evaluation is an evaluation strategy that delays computing an expression until its value is needed.
- comptime parserComptime parsing is the compile-time transformation of raw input data into program values or data structures.
- comptime type parameterA comptime type parameter is a Zig function parameter whose type value is supplied and evaluated at compile time.
- generic functionA generic function is a function defined with type or value parameters so it can operate across multiple concrete instantiations.
- labelA label is a name attached to a block or loop that permits targeted break control flow.
- labeled blockA labeled block is a named Zig block that can be exited with break and can yield a value.
- std.mem.tokenizeScalarstd.mem.tokenizeScalar is a Zig standard-library generic function that returns an iterator splitting text on a scalar delimiter.
- TCPTCP is the Transmission Control Protocol, a transport-layer protocol that provides reliable ordered byte-stream communication between hosts.
- HTTPHTTP is an application-layer network protocol that defines request and response semantics for transferring hypertext and related resources.
- echo serverThe echo server is the book's example server program that returns processed request text to clients.
- comptimeComptime is Zig's compile-time execution feature that allows code to be evaluated during compilation.
- error setAn error set is the statically specified set of error values that a function may produce.
- interfaceAn interface is an abstraction that exposes defined operations or services while hiding underlying implementation details.
- separation of concernsSeparation of concerns is a design principle that partitions a system so each component addresses a limited set of related responsibilities.
- modularityModularity is the organization of software into separable components with focused responsibilities and reusable interfaces.
- standard libraryA standard library is the collection of general-purpose modules and APIs distributed as part of a programming language implementation.
- error handlingError handling is the representation and handling of failures that can occur during program execution.
- error unionAn error union is a Zig type whose values contain either an error or a payload value of an inner type.
- @compileLog@compileLog is a Zig builtin that emits compile-time diagnostic output and prevents successful final compilation.
- @embedFile@embedFile is a Zig compile-time builtin that embeds a file's contents into a program as a byte slice.
- break statementbreak is a control-flow construct that exits a loop or labeled block, optionally producing a value.
- comptime memorizationComptime memoization is the Zig compiler's caching of a compile-time function result for repeated calls with the same input.
- duck typingDuck typing is accepting a value based on whether its available operations satisfy the code's requirements rather than on an explicitly declared interface.
- std.Iostd.Io is Zig's standard-library interface for portable input/output operations, including buffered and concurrent I/O.
- sliceA slice is a view representing a portion of a contiguous sequence of elements, typically through a pointer and a length.
- hermetic build systemBuild hermeticity is the property that a build's results depend only on declared, self-contained inputs rather than external environment state.
These guides are generated from the text of Manning books by Manning's knowledge graph and link to the sections they draw on. The full books are available on liveBook and at manning.com.
