Chapter 2: A practical guide
The introduction frames Zig as a pragmatic language and explains why the book teaches basics before moving to practical projects.
After this chapter you will be able to
- Pragmatism and practical learning. Explain why the book emphasizes real-world projects while first covering Zig basics.
- Standard Library Import and Access. Explain how a Zig program imports the standard library and accesses a function within it.
- Function Bodies and Runtime Flow. Trace where runtime statements live and how execution reaches called functions.
- Compile Time and Runtime. Distinguish when comptime code and runtime code execute.
- Const and var declarations. Distinguish const from var and explain why Zig reports an error when a var is never changed or a const is mutated.
- Static typing and inference. Explain when Zig can infer a variable’s type and why an explicit type is needed for the section’s integer example but not its boolean example.
- Function parameters and returns. Explain the types and return rules in the Fibonacci example: n is a const usize parameter, the function returns i32, and a non-void return must supply a value of the return type.
- Checked and wrapping arithmetic. Explain why a sufficiently large Fibonacci calculation panics in safe mode and how wrapping arithmetic differs.
- Control flow as expressions. Explain how Zig treats if/else and other control flow as expressions, including else if and apparently valueless cases.
- Public source-file declarations. Explain that pub makes a function or variable accessible to other source files that import its file, as with the Fibonacci function.
- Imports as namespaces. Describe how @import can take a relative path to a Zig source file and how its result lets code access declarations from that file.
- Scalability through composability. Explain why Zig can support serious programs despite having a small set of basic tools.
- Raw pointers and memory risks. Explain that Zig uses raw machine pointers, which are memory addresses, and that their permissiveness allows both direct control and invalid memory access.
- Single-item pointer types. Describe what a single-item pointer holds and how Zig writes its type, such as *i32.
- Address and dereference operators. Explain how & obtains a value’s address and how .* retrieves the item at a pointer’s address.
- Pointer mutability and coercion. Explain why writing through a pointer to constant data is rejected, why a mutable pointer can be coerced to *const i32, and what a parameter’s pointer type communicates.
- Array value copies and mutability. Explain what happens when one Zig array variable is assigned to another, and why a copy must be declared var if its elements will be changed.
- Pointers for array mutation. Explain why passing an array directly to a function does not let it mutate the original array, and describe the pointer types presented as an alternative and their length limitation.
- Slice representation and safety. Explain what a Zig slice contains, how it differs from an array, and how its length supports bounds-checked indexing.
- Range slicing boundaries. Explain how a range selects elements from an array or slice, including its endpoints and the compile-time range result.
- Buffers as temporary storage. Explain that a buffer is temporary storage commonly supplied by the programmer to a function, typically as a `[]u8` slice of mutable bytes.
- Explicit uninitialized buffer creation. Describe how assigning an array `undefined` creates an uninitialized buffer, and explain why its contents must not be read before initialization.
- Strings as encoded slices. Explain why Zig commonly uses slices for strings rather than a dedicated string type.
- String literal pointer type. Describe the type of the example string literal and why its bytes can be used through a pointer or a slice.
- Purposes of pointer-related types. Explain that Zig offers multiple pointer-related types for memory-related code and that each serves a distinct purpose, rather than being an interchangeable option.
- Struct fields and initialization. Explain that a Zig struct groups named values into one composite type, that field names must be unique, and that every field must be initialized.
- Structs as namespaces. Explain that structs can contain function and variable declarations as well as fields, so a struct can serve as a namespace without grouping data. Describe how the compiler treats a source file as though its code were enclosed in a struct body.
- Struct function dot syntax. Explain that a function declared inside a struct can be called with dot syntax when its first parameter has the struct’s type; that parameter refers to the instance used in the call.
- Value copies and pointer mutation. Distinguish a struct value parameter from a pointer parameter: `Rectangle.size` receives a copy through its value parameter, while a function that modifies the rectangle needs a `*Rectangle` parameter.
- Constants and initializer functions. Describe how a struct can provide an empty instance through a constant or initialization behavior through a function, and how Zig resolves .empty and .init() from context.
- Intent of explicit initializers. Explain why the section favors initializer constants and functions over relying on default field values.
- Minimal Zig struct model. Describe Zig structs as collections of fields and declarations with some syntax sugar, rather than object-oriented types with inheritance or virtual method tables.
What it builds on
- Do it at comptime (chapter 1) · Introduces comptime as a Zig idea.
Section by section
Introduction
The introduction frames Zig as a pragmatic language and explains why the book teaches basics before moving to practical projects.
- Pragmatism and practical learning: Explain why the book emphasizes real-world projects while first covering Zig basics.
Why it matters: This explains why the chapter starts with fundamentals despite the book’s hands-on focus.
Key terms: real-world pragmatism, basics, projects with real-world application
2.1 The anatomy of a Zig program
This section introduces the imports, modules, functions, and execution-time distinctions in a simple Zig program.
- Standard Library Import and Access: Explain how a Zig program imports the standard library and accesses a function within it.
Why it matters: It lets you read how the program reaches functions supplied by the standard library. - Builtins and Module Boundaries: Describe what Zig builtins and modules are at the level introduced here.
Why it matters: These terms explain what @import is and what kind of code it brings into a program. - Function Bodies and Runtime Flow: Trace where runtime statements live and how execution reaches called functions.
Why it matters: It gives you a basic way to follow what runs when a Zig program executes. - Compile Time and Runtime: Distinguish when comptime code and runtime code execute.
Why it matters: The distinction prevents you from treating compiler execution and program execution as the same event.
Key terms: std, @import, namespace, std.debug.print, builtin, module, root source file, @ prefix, function body, block
2.1.1 Variables
This section explains how Zig declares variables, chooses between const and var, and determines and enforces their types.
- Const and var declarations: Distinguish const from var and explain why Zig reports an error when a var is never changed or a const is mutated.
Why it matters: Choosing const or var correctly is part of writing declarations Zig will accept. - Static typing and inference: Explain when Zig can infer a variable’s type and why an explicit type is needed for the section’s integer example but not its boolean example.
Why it matters: This explains why some declarations need an explicit type even though many do not. - Explicit type conversions: Explain what strongly typed means here and describe what Zig requires when converting between types such as boolean and integer or integer and float.
Why it matters: An inferred or declared type does not mean Zig will silently convert a value to another type.
Key terms: const, var, statically typed, type annotation, inferred, i32, bool, strongly typed, type coercion
2.1.2 Basic types
Introduces Zig’s basic types in the context of type annotations and points readers to a table that is not included in the supplied text.
2.1.3 Functions
Uses a recursive Fibonacci example to explain Zig function signatures and returns, overflow behavior, and conditional expressions.
- Function parameters and returns: Explain the types and return rules in the Fibonacci example: n is a const usize parameter, the function returns i32, and a non-void return must supply a value of the return type.
Why it matters: These rules help you read a function’s contract and understand why an invalid return fails to compile. - Checked and wrapping arithmetic: Explain why a sufficiently large Fibonacci calculation panics in safe mode and how wrapping arithmetic differs.
Why it matters: It explains why ordinary integer addition can fail at runtime and how to choose wrapping deliberately. - Boolean conditional requirements: Describe what Zig requires of an if condition.
Why it matters: It prevents carrying over conditional syntax and truthiness assumptions from other languages. - Control flow as expressions: Explain how Zig treats if/else and other control flow as expressions, including else if and apparently valueless cases.
Why it matters: Thinking of control flow as expressions makes Zig’s conditional syntax and value-producing branches easier to understand.
Key terms: usize, i32, const, void, return, integer overflow, safe mode, runtime panic, +, +%
2.1.4 Back to modules
This section uses a Fibonacci example to explain how Zig source files expose declarations, how @import accesses them, and why main must be public.
- Public source-file declarations: Explain that pub makes a function or variable accessible to other source files that import its file, as with the Fibonacci function.
Why it matters: It explains the change that lets the split-file Fibonacci example work. - Imports as namespaces: Describe how @import can take a relative path to a Zig source file and how its result lets code access declarations from that file.
Why it matters: It connects source-file imports with the names used to reach their declarations. - Public main and startup: Explain why main is declared pub and how Zig’s start code reaches it.
Why it matters: The same import-and-visibility rule also explains how a program’s entry point is called.
Key terms: pub, source file, @import, namespace, declarations, main, start code, root
2.1.5 That’s it?
This section explains why Zig’s small set of program-building tools can still scale to serious work.
- Scalability through composability: Explain why Zig can support serious programs despite having a small set of basic tools.
Why it matters: It explains why learning a few basic pieces is enough to start building larger Zig programs.
Key terms: composability, interchangeable parts, well-refined semantics
2.2 Pointing You in the Right Direction
Introduces Zig pointers as raw memory addresses whose permissiveness provides flexibility while allowing memory-access errors.
- Raw pointers and memory risks: Explain that Zig uses raw machine pointers, which are memory addresses, and that their permissiveness allows both direct control and invalid memory access.
Why it matters: This tradeoff explains both the control pointers provide and the care they demand. - Segmentation fault meaning: Describe a segmentation fault as a crash caused by accessing an address outside the memory the operating system permits the program to use.
Why it matters: It gives a precise meaning to one of the pointer-related failures the section names. - Pointers across programming tasks: Describe how pointer permissiveness can remove abstraction layers and support several uses, such as mutating data, representing strings, and referencing arrays.
Why it matters: These uses show why programmers accept the risks of direct memory access.
Key terms: raw machine pointers, memory addresses, uninitialized, segmentation fault, segfault, mutating data, strings, arrays, function pointers
2.2.1 Single-Item Pointers
This section explains how Zig single-item pointers represent and access one value, and how the referenced value’s mutability affects pointer use.
- Single-item pointer types: Describe what a single-item pointer holds and how Zig writes its type, such as *i32.
Why it matters: The type tells you what kind of individual value the pointer addresses. - Address and dereference operators: Explain how & obtains a value’s address and how .* retrieves the item at a pointer’s address.
Why it matters: These operators let you connect a value to its pointer and access the value through that pointer. - Pointer mutability and coercion: Explain why writing through a pointer to constant data is rejected, why a mutable pointer can be coerced to *const i32, and what a parameter’s pointer type communicates.
Why it matters: Pointer constness helps the compiler prevent writes and helps readers judge whether a function may change their data.
Key terms: single-item pointer, item, *i32, &, .*, dereference, mutable pointer, constant pointer, *const i32, coerce
2.2.2 Arrays
This section explains Zig array syntax, value-copying behavior, and why functions may take a pointer when they need to mutate an array.
- Array types and indexing: Describe how [N]T specifies an array’s element count and type, how _ lets the compiler infer the count during initialization, and how bracketed zero-based indexes access elements.
Why it matters: The type and indexing syntax let you read and write basic Zig array code. - Array value copies and mutability: Explain what happens when one Zig array variable is assigned to another, and why a copy must be declared var if its elements will be changed.
Why it matters: Value copying changes what you should expect when modifying an assigned array. - Pointers for array mutation: Explain why passing an array directly to a function does not let it mutate the original array, and describe the pointer types presented as an alternative and their length limitation.
Why it matters: It explains when copying is unsuitable and why the next section introduces slices.
Key terms: [N]T, inferred element count, zero-indexed, arrays are values, arr_copy, const, var, *[N]T, *const [N]T, single-item pointer
2.2.3 Slicing and dicing
This section explains how Zig slices represent and safely access a variable number of elements, how they compare with many-item pointers, and how to obtain them from arrays and ranges.
- Slice representation and safety: Explain what a Zig slice contains, how it differs from an array, and how its length supports bounds-checked indexing.
Why it matters: Slices let you work with data of varying lengths without losing track of its bounds. - Many-item pointer tradeoff: Distinguish a many-item pointer from a slice and explain when the section suggests using one.
Why it matters: The comparison explains what safety and convenience the slice's length buys you. - Whole-array slice coercion: Describe how a pointer to an array can become a slice referencing the entire array.
Why it matters: This gives you a slice of a whole array without specifying its bounds manually. - Range slicing boundaries: Explain how a range selects elements from an array or slice, including its endpoints and the compile-time range result.
Why it matters: Range boundaries let you describe a portion of existing data without treating every range result as the same type.
Key terms: slice, []T, []const T, ptr, len, safe mode, many-item pointer, [*]T, [*]const T, coerce
2.2.4 Buffers and Undefined
This section explains how Zig programs use byte buffers, how `undefined` can create an uninitialized buffer, and why reading that buffer before writing to it is dangerous.
- Buffers as temporary storage: Explain that a buffer is temporary storage commonly supplied by the programmer to a function, typically as a `[]u8` slice of mutable bytes.
Why it matters: This explains why a Zig function may ask you to provide space for its work. - Explicit uninitialized buffer creation: Describe how assigning an array `undefined` creates an uninitialized buffer, and explain why its contents must not be read before initialization.
Why it matters: An uninitialized buffer provides storage to write into, not values that are safe to read. - Writer buffer in practice: Explain the section's stdout writer example: it accepts a `[]u8`, is given a `*[1024]u8`, and writes into that buffer to reduce how often stdout output blocks the program.
Why it matters: The example shows a concrete benefit of giving a function a buffer.
Key terms: buffer, array, slice, []u8, undefined, uninitialized, stdout_file.writer, *[1024]u8, stdout
2.2.5 I’ve been Stringing You Along
This section explains how Zig represents strings and character literals using byte sequences, pointers, slices, and integer values rather than dedicated string or character types.
- Strings as encoded slices: Explain why Zig commonly uses slices for strings rather than a dedicated string type.
Why it matters: It explains why string-handling code in Zig often takes a slice rather than a special string value. - String literal pointer type: Describe the type of the example string literal and why its bytes can be used through a pointer or a slice.
Why it matters: The literal's pointer type explains both its efficient use and why ordinary slice-based tools accept it. - Literal nul termination: Explain what the :0 in the string literal's type indicates and why it is useful.
Why it matters: The terminator is part of why a Zig string literal can work directly with C functions. - Character literal integer values: Describe how Zig spells and types character literals, including how their values can coerce to integer types.
Why it matters: It clarifies why a quoted character can be used as an integer value without a separate built-in character type.
Key terms: string type, UTF-8, slices, string literal, single-item pointer, u8, []const u8, coerce, :0, nul terminator
2.2.6 A few points to review
This review emphasizes that Zig’s pointer-related types have distinct purposes when writing code that deals with memory.
- Purposes of pointer-related types: Explain that Zig offers multiple pointer-related types for memory-related code and that each serves a distinct purpose, rather than being an interchangeable option.
Why it matters: This helps you recognize why choosing a pointer-related type matters, even though this review does not spell out the choices.
Key terms: pointer-related types, expressive type system
2.3 Structs
This section introduces Zig structs as composite values, explains how their fields are initialized and accessed, and shows how structs can be used as values.
- Struct fields and initialization: Explain that a Zig struct groups named values into one composite type, that field names must be unique, and that every field must be initialized.
Why it matters: This is the basis for reading and creating structs in Zig. - Accessing struct fields: Describe how to access an individual field of an initialized struct.
Why it matters: Field access lets you use the data grouped inside a struct. - Structs as values: Explain that structs are values that can be passed to functions or used as fields of other structs.
Why it matters: Treating structs as values makes it possible to combine them with functions and other structs.
Key terms: struct, composite type, fields, dot syntax, structs, values, function parameters
2.3.1 Structs are also namespaces
This section shows that a Zig struct can hold declarations and serve as a namespace without grouping data.
- Structs as namespaces: Explain that structs can contain function and variable declarations as well as fields, so a struct can serve as a namespace without grouping data. Describe how the compiler treats a source file as though its code were enclosed in a struct body.
Why it matters: This explains why you may see a struct used to organize names even when it holds no data.
Key terms: struct, namespace, fields, declarations, source files
2.3.2 Methods, sort of
Explains Zig’s method-like dot syntax for struct functions and why mutating an instance requires a pointer parameter.
- Struct function dot syntax: Explain that a function declared inside a struct can be called with dot syntax when its first parameter has the struct’s type; that parameter refers to the instance used in the call.
Why it matters: This lets you read dot calls without mistaking them for a separate object-oriented mechanism. - Value copies and pointer mutation: Distinguish a struct value parameter from a pointer parameter: `Rectangle.size` receives a copy through its value parameter, while a function that modifies the rectangle needs a `*Rectangle` parameter.
Why it matters: The parameter type tells you whether a struct function receives a copy or can modify the original.
Key terms: struct, dot syntax, method syntax, Rectangle.size, *Rectangle, value, copy
2.3.3 Struct initialization in the wild
This section explains common Zig struct initialization patterns and why explicit initializers can be preferable to default field values.
- Constants and initializer functions: Describe how a struct can provide an empty instance through a constant or initialization behavior through a function, and how Zig resolves .empty and .init() from context.
Why it matters: These are common ways to create structs in Zig libraries. - Intent of explicit initializers: Explain why the section favors initializer constants and functions over relying on default field values.
Why it matters: An initializer gives callers a clearer, more stable way to create a struct. - Implicit default field changes: Explain what happens to omitted fields with defaults during struct initialization and why changing a default can have surprising effects.
Why it matters: A changed default can alter existing struct creations without any change at their call sites.
Key terms: Stack.empty, Stack.init(), .empty, .init(), initializer functions, initializer constants, default field values, canned_tuna
2.3.4 Simple and sweet
This section sums up Zig structs as deliberately simple and connects that simplicity to Zig’s different design priorities.
- Minimal Zig struct model: Describe Zig structs as collections of fields and declarations with some syntax sugar, rather than object-oriented types with inheritance or virtual method tables.
Why it matters: This gives you the right starting point for reading a Zig struct without assuming familiar object-oriented machinery. - Different Zig design priorities: Explain the section’s interpretation of why some tasks may feel difficult in Zig: its priorities differ from those of popular languages, so it may expect a different approach.
Why it matters: It helps explain why Zig’s bare-bones structs may feel unfamiliar without assuming the section has taught an alternative technique.
Key terms: structs, fields, declarations, inheritance, virtual method tables, syntax sugar, priorities, ergonomics
2.4 Summary
Where this is used later
- Thinking in comptime (chapter 4) · Builds on the distinction between compiler-time and runtime execution.
- Register instructions and overflow operators (chapter 6) · Overflow operators recur in register instructions.
- Executing our plan (chapter 4) · Program logic can build on the idea that control flow is expression-based.
- For loops (chapter 3) · the earlier introduction to arrays
- To buffer, or not to buffer (chapter 3) · arrays and their sizes
- What using the C ABI looks like (chapter 5) · C interoperability can use the distinction between pointers with and without an attached length.
- Strings without slices (chapter 5) · Provides the Zig-side understanding of strings for the later discussion of strings across the C boundary.
- Making it useful (chapter 5) · Earlier treatment of strings.
Concepts explained in this chapter
- single-item pointerA single-item pointer is a pointer type whose referent is one item rather than an indexed sequence of items.
- sliceA slice is a view representing a portion of a contiguous sequence of elements, typically through a pointer and a length.
- structA struct is a composite type that groups named fields and can also contain associated declarations or functions.
- namespaceA namespace is a named scope that groups program declarations and prevents naming conflicts.
- functionA subroutine is a callable sequence of instructions that returns control to its caller when complete.
- @import@import is a Zig builtin function and expression that loads Zig code from a module or file and returns a type containing its declarations.
- main functionA main function is the designated entry point that begins execution of a program.
- comptimeComptime is Zig's compile-time execution feature that allows code to be evaluated during compilation.
- moduleA module is a source-code unit that groups related declarations and functionality within a program.
- multi-item pointerA many-item pointer is a Zig pointer type that represents the address of an unspecified number of contiguous elements without storing their length.
- pointerA pointer type represents values that refer to memory locations or other objects.
- type hintsA type annotation is source-code syntax that explicitly specifies the type of a value, variable, parameter, or other program element.
- null terminationA NUL terminator is a zero byte placed after text data to mark the end of a byte string.
- standard libraryA standard library is the collection of general-purpose modules and APIs distributed as part of a programming language implementation.
- bufferA buffer is a temporary memory area that holds data before it is processed or transferred.
- ZigZig is a general-purpose systems programming language designed for reliable, maintainable, performant software with minimal dependencies and explicit control over low-level behavior.
- composabilityComposability is the property of software parts being combineable into larger systems through well-defined interactions.
- int32i32 is Zig's signed 32-bit integer type.
- type coercionType coercion is the conversion of a value from one type to another so that an operation can accept it.
- WrappingAddWrapping addition is integer addition that returns the modulo-width result when the mathematical sum overflows.
- integer overflowInteger overflow occurs when an arithmetic result cannot be represented in the destination integer type's range.
- type inferenceType inference is compiler deduction of a program expression's data type from its context and values.
- void typeVoid is a type representing the absence of a return value.
- interfaceAn interface is an abstraction that exposes defined operations or services while hiding underlying implementation details.
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.
