Introduction: Why Zig?
- The Systems Programming Landscape Today
- Andrew Kelley’s Vision and the Origin of Zig
- No Hidden Control Flow: The Core Philosophy
- Where Zig Fits Among C, C++, Rust, and Go
- How This Book Is Organized
Chapter 1: Getting Started - Installation, Toolchain, and Your First Program
- Installing Zig: Official Releases and Building from Source
- The Zig Compiler Driver:
zig build-exe,zig run,zig test - Your First Program: A Walkthrough of main.zig
- Understanding the Zig Build System (
build.zig) - Project Layout Conventions and the Standard Library
Chapter 2: Types, Variables, and Constants - The Building Blocks
- Primitive Types: Integers, Floats, Booleans, and the Void Type
- Variable Declarations:
varvsconstand Immutability by Default - Type Inference and Explicit Typing
- Integer Overflow Semantics: Safe, Wrapping, Saturating, and Unchecked
- The Undefined Behavior Problem Zig Eliminates
Chapter 3: Control Flow - Branching, Looping, and the Block Expression
- If/Else as Expressions: Values Everywhere
- The Switch Statement: Exhaustive Pattern Matching Without Patterns
- While Loops: Tags, Break Values, and Control Flow Clarity
- For Loops: Arrays, Slices, Enumerators, and the New Syntax
- Block Expressions and Local Scoping
Chapter 4: Pointers, Arrays, and Slices - Memory in Zig
- Pointer Types: Single (
*T) vs Multi ([*]T) Pointers - Const Correctness in Pointers:
*const Tand Nested Const - Arrays as First-Class Value Types: Length Is Part of the Type
- Slices: Fat Pointers, Bounds Checking, and Ownership Semantics
- How Zig’s Pointer Model Differs from C
Chapter 5: Structs, Enums, and Unions - Composite Types
- Struct Definitions: Fields, Default Values, and Initialization
- Methods and the Self Parameter
- Enums: Values, Tags, Sentinels, and Iteration
- Unions and Tagged Unions (
union(enum)): Safe Variant Types - Packed Structs and Extern Structs for Binary Layout Control
Chapter 6: Optionals, Error Sets, and Error Unions - Safety Without Exceptions
- Optionals: The
T?Type and Safe Null Handling - Error Sets as Compile-Time Types
- The
tryOperator: Propagating Errors Explicitly - Error Unions (
T!E) and thecatchOperator errdefer: Cleanup on Error Return- Why Zig Rejects Exceptions: Design Rationale
Chapter 7: Functions, Generics, and Compile-Time Programming - Zig’s Superpower
- Function Declarations: Parameters, Return Types, and Conventions
- Inline Functions and Call-Site Inlining
- The
comptimeKeyword: When Code Runs at Compile Time - Type Parameters and Generic Functions
- Building Generic Data Structures: A Linked List from Scratch
- Comptime Blocks and Compile-Time Assertions
Chapter 8: Memory Management - Explicit Allocation, No Garbage Collector
- The Allocator Parameter: Passing Memory Responsibility Explicitly
- GeneralPurposeAllocator and the Standard Library Allocators
- ArenaAllocator: Scope-Based Allocation for Temporary Data
- FixedBufferAllocator and Stack-Backed Allocation
- Manual Memory Management Patterns and Common Mistakes
- Implementing Custom Allocators
- Summary
Chapter 9: Strings, Formatting, and I/O - Working with Text
- Strings Are UTF-8 Byte Slices: Encoding Semantics
- String Comparison, Concatenation, and Allocation-Free Operations
- Formatting:
std.fmtFormatters and Custom Format Implementations - File I/O: Readers, Writers, and the Buffering Layer
- Path Handling and Directory Traversal
Chapter 10: The Build System, Package Management, and C Interop
- The Build System (
build.zig) in Depth: Steps, Options, and Artifacts - Cross-Compilation: Zig’s Built-In Multiplatform Story
- Module System and Package Management
- Importing C Libraries: Build-System C Translation
- Exporting to C: FFI in the Other Direction
Chapter 11: Testing, Debugging, and Tooling - Building Reliable Software
- The Built-In Test Framework:
zig testand Test Organization - Assertion Macros and Custom Error Messages
- Debugging with GDB and LLDB
- Sanitizers: AddressSanitizer, UndefinedBehaviorSanitizer, and ThreadSanitizer
- Profiling and Performance Analysis Tools
Chapter 12: Concurrency - Threads, Atomics, and Synchronization
- Threads:
std.Threadand the Spawn API - Atomic Operations: Load, Store, Compare-and-Swap, and Ordering
- Mutexes, RWLocks, and Condition Variables
- Channel-Based Communication Patterns
- Concurrency Pitfalls and Safe Patterns
Chapter 13: Real-World Projects - Case Studies in Idiomatic Zig
- Case Study 1: Building a Command-Line JSON Parser
- Case Study 2: A Simple HTTP Server from Scratch
- Case Study 3: A Binary Protocol Encoder and Decoder
- Project Structure Best Practices for Larger Codebases
- Performance Optimization: Benchmarking, Profiling, and Tuning
Chapter 14: Async I/O and Event-Driven Programming
- The Problem with Threads: Scaling I/O-Bound Workloads
- The
std.IoInterface: I/O as an Injectable Dependency - Juicy Main and the I/O Context
- Asynchronous Operations:
io.async()andFuture - Concurrent Tasks with
GroupandBatch - Cancellation: Preventing Resource Leaks
- Evented I/O: io_uring and Performance
- Async Networking: Building a Scalable HTTP Server
- Summary of Async I/O Patterns
Chapter 15: Compile-Time Reflection and Advanced Metaprogramming
- Beyond Generics: What
comptimeCan Really Do @typeInfo: Reading Type Metadata@field,@typeOf, and Field Access by Name- Building a Generic JSON Serializer with Reflection
- Programmatic Type Construction:
@Int,@Struct,@Pointer, and Friends @offsetOf,@ptrToInt, and Layout Inspection- Comptime Assertions and Compile-Time Validation
- Metaprogramming Patterns: Adding Methods to Generated Types
- When to Use Reflection vs. Explicit Code
- Summary
Chapter 16: SIMD, Bit Manipulation, and Low-Level Programming
- Why Low-Level Control Matters
- Vectors and SIMD: Parallel Operations on Data
- Bit Manipulation: Working at the Bit Level
- Endianness: Handling Different Byte Orders
- Packed Structs: Exact Control of Memory Layout
- Volatile Access and Memory-Mapped Hardware
@bitCast,@ptrToInt, and Low-Level Type Conversions- SIMD and Bit Manipulation in Practice: A Substring Search
- Summary
Chapter 17: WebAssembly Compilation and JavaScript Interop
- Why Zig for WebAssembly?
- WASM Target Variants: Choosing the Right Environment
- Your First WASM Module: Exporting Functions to JavaScript
- Working with Linear Memory
- Optimizing WASM Binaries for Size and Speed
- WASM SIMD: Using
@Vectorin the Browser - Using zig-js: Simplified JavaScript Interop
- WASI: Server-Side Zig in WebAssembly
- Summary
Chapter 18: Embedded Systems and Freestanding Environments
- Why Zig for Embedded Development?
- Freestanding Targets: No OS, No libc, No Problem
- Linker Scripts: Defining Memory Layout
- Startup Code: From Reset to main()
- Hardware Register Access with Packed Structs
- Interrupt Handling
- UART Communication
- Using the Standard Library in Freestanding Environments
- Debugging Embedded Zig Programs
- MicroZig and Embedded Toolchains
- Summary
Chapter 19: Operating System Integration - Processes, Signals, and Resources
- The OS Interface Layer:
std.os,std.posix, and Platform Abstraction - Process Spawning and Management
- Signal Handling
- File Descriptors and I/O Multiplexing
- Environment Variables and Process Arguments
- Pipes and Process Communication
- Summary
Chapter 20: Zig as a C Compiler and libc Replacement
- The Zig Toolchain Beyond Zig Code
- How
zig ccWorks Internally - Compiling C Code with
zig cc - Bundled libc Implementations
- glibc Version Targeting
- Using
zig ccas a Drop-In Replacement - Zig libc and the Future of C Interoperability
- C++ Compilation with
zig c++ - Compiling Mixed Zig and C Projects
- Summary
Chapter 21: Cross-Compilation Deep Dive
- Why Zig’s Cross-Compilation Is Different
- Target Triples: Anatomy of a Cross-Compilation Target
- Listing and Discovering Targets
- Practical Cross-Compilation Scenarios
- Using Cross-Compilation with the Build System
- Cross-Compiling C Dependencies with
zig cc - Testing Cross-Compiled Binaries
- Freestanding and Embedded Targets
- Summary
Chapter 22: Security, Hardening, and Defensive Programming
- The Security Posture of Zig Programs
- Compiler Safety Checks Across Build Modes
- AddressSanitizer (ASAN): Detecting Memory Errors
- UndefinedBehaviorSanitizer (UBSAN): Catching Undefined Behavior
- ThreadSanitizer (TSAN): Detecting Data Races
- The Fuzzer: Finding Bugs with Smith
- Defensive Input Validation
- Memory Protection and Hardening
- Secure Secrets Handling
- Supply Chain Security
- Summary
Chapter 23: Performance Optimization and Benchmarking
- The Optimization Landscape in Zig
- Understanding Build Modes and Performance
- Measuring Performance: Manual Timing
- Using zBench for Structured Benchmarking
- Profiling with perf (Linux)
- Identifying Common Bottlenecks
- Compiler Inlining and Function Calls
- Summary
Chapter 24: Building Language Tools with Zig
- Why Zig Excels for Language Tooling
- Using the Built-in Tokenizer
- Writing a Simple Parser
- Generating Code at Comptime
- Building a Linter or Static Analyzer
- Summary
Chapter 25: The std.Io Interface Deep Dive
- The I/O Overhaul in Zig 0.16
- The Io Interface
- File Operations with std.Io
- Streams: Readers and Writers
- Mocking I/O for Testing
- Summary
