Zig Tutorial
Learn Zig step by step: 37 lessons in 9 chapters with examples, quizzes, diagrams and projects.
Start learning →
of lessons completed
Getting Started
- What Is Zig? Meet Zig, a small systems programming language with no hidden control flow, no hidden allocations and compile-time code execution. Learn what it is for and how it compares.
- Installing Zig Install the Zig compiler on Windows, macOS or Linux, check it with zig version, set up an editor with ZLS, and manage multiple Zig versions as a beginner.
- Your First Zig Program Write, run and understand your first Zig program: the std import, pub fn main, std.debug.print format strings, and writing to standard output with the 0.15 writer.
- Program Structure and Imports Understand how a Zig program is organized: every file is a struct, top-level declarations, pub visibility, importing your own files, comments, doc comments and test blocks.
- Compiler Commands and Build Modes Learn the everyday zig commands (run, build-exe, test, fmt, init, build, cc), the four build modes Debug, ReleaseSafe, ReleaseFast and ReleaseSmall, and what each one checks.
Language Basics
- Variables and Constants Learn how Zig declares names with const and var, why const is the default, type inference, undefined, comptime_int, no-shadowing rules and unused variable errors.
- Integers and Floating-Point Numbers Master Zig numeric types: i8 to i128, u8 to u64, usize, arbitrary bit widths, f32 and f64, overflow operators +% and +|, @intCast, @as and @floatFromInt.
- Booleans and Operators Learn Zig's bool type and every operator: arithmetic, comparison, and/or/not as words, bitwise and shift operators, compound assignment, precedence and common pitfalls.
- Arrays and Slices Learn Zig arrays and slices: [N]T fixed-size arrays, [_] inference, indexing and bounds checks, slicing with ranges, []const T, multidimensional arrays and sentinel-terminated arrays.
- Strings and Characters Learn how Zig handles text: strings as byte slices, string literals and sentinels, multiline strings, comparing with std.mem.eql, searching, splitting, formatting and UTF-8 basics.
Control Flow and Functions
- if and switch Learn Zig conditionals: if as an expression, else if chains, unwrapping optionals with if, switch with ranges, multiple values, captures, exhaustiveness, else and labeled switch.
- Loops Learn Zig loops: while with continue expressions, for over slices and ranges, indexes, multiple sequences, break with values, labeled loops, else clauses and inline for.
- Functions Learn to write Zig functions: parameters are constants, return types, multiple results with structs, recursion, function pointers, anytype, inline, noreturn and doc comments.
- defer and errdefer Learn Zig's defer and errdefer: run cleanup when a scope ends, execution order, pairing allocation with free, errdefer on failure, defer in loops and blocks, and common pitfalls.
Types and Memory
- Pointers Understand Zig pointers: *T single-item pointers, address-of and dereference, const pointers, many-item [*]T, slices vs pointers, optional pointers, alignment and dangling pointer risks.
- Structs Learn Zig structs: declaring fields, default values, initialization with .{}, methods and self, init and deinit conventions, nested and anonymous structs, tuples and the @This builtin.
- Enums and Unions Learn Zig enums and unions: enum values and backing types, methods on enums, @tagName and @intFromEnum, bare and tagged unions, switch with captures, and modeling states safely.
- Optionals Learn Zig optionals: the ?T type, null, orelse defaults, .? unwrapping, if and while captures, optional pointers, chaining and why Zig has no null reference bugs.
- Memory Layout and Alignment Understand where Zig values live: stack versus heap, sizes and alignment with @sizeOf and @alignOf, padding, extern struct for C layout, packed struct for bits, and how to read memory safely.
Allocators and Error Handling
- Allocators in Zig Learn why Zig passes allocators explicitly, and how the page, arena, fixed-buffer and debug allocators differ, with diagrams, examples and a runnable arena stand-in.
- Allocating and Freeing Memory Allocate slices and single items in Zig with alloc, create, dupe and realloc, free them with defer, and avoid leaks and use-after-free, with examples and a Go stand-in.
- ArrayList and Hash Maps Use std.ArrayList and the hash map family in Zig: append, pop, insert, getOrPut, iterate, string keys and ownership rules, with examples and a runnable Go stand-in.
- Error Unions and try Understand Zig errors as values: error sets, error union types like !T, try, catch, if/else capture, switching on errors and error return traces, with Go stand-ins.
- errdefer and Custom Error Sets Clean up safely when things fail in Zig: defer versus errdefer, error captures, designing custom error sets, merging sets, anyerror and diagnostics, with a Go stand-in.
Comptime and Generics
- Comptime Basics Learn Zig comptime: running ordinary code at compile time, comptime parameters and variables, comptime-known sizes, compile errors, inline loops and limits, with examples.
- Generic Functions with comptime Write generic functions in Zig with comptime type parameters, anytype, type inference with @TypeOf, constraints via @typeInfo and @compileError, with examples and Go generics.
- Generic Data Structures Build generic containers in Zig by returning a struct type from a function: a stack, a linked list and a queue, with allocators, deinit, iterators and a Go generics stand-in.
- Type Reflection and Comptime Tricks Inspect types at compile time in Zig with @typeInfo, @fieldParentPtr, @field and inline for, generate code from struct fields, build lookup tables and write a tiny printer.
C Interop and Build System
- Calling C from Zig Use C libraries from Zig with @cImport and translate-c, map C types and pointers, pass strings and callbacks, export Zig functions to C, and link libc, with a runnable C counterpart.
- The Zig Build System Learn zig build and build.zig: executables, libraries, run and test steps, optimize modes, custom options, linking C, installing artifacts and a complete example file.
- Packages and Modules Organize Zig code with files as structs, @import, pub, and root modules, then add dependencies with build.zig.zon, zig fetch, content hashes and addImport, with a runnable hash stand-in.
Concurrency and Tooling
- Threads and Synchronization Run code in parallel in Zig with std.Thread.spawn and join, protect shared data with Mutex and atomics, use Condition, thread pools and WaitGroup, and avoid data races.
- Testing in Zig Write and run tests in Zig with test blocks, std.testing expect functions, testing.allocator leak detection, error tests, table-driven tests, filters and zig build test.
- Cross-Compiling and Tooling Build for other operating systems and CPUs from one machine with Zig targets, use zig cc as a C compiler, format code with zig fmt, debug with traces, and set up editors and ZLS.
Projects and Practice
- Project: Word Frequency Counter Build a word frequency counter in Zig step by step using slices, tokenizing, a StringHashMap, an arena for owned keys, sorting and tests, with a runnable Go version of the same design.
- Project: A Stack-Based Calculator VM Build a small stack-based calculator in Zig using tagged unions, switch, error sets, a tokenizer for postfix expressions and a fixed-size stack, with tests and a runnable Go version.
- Zig Practice Exercises Twelve Zig exercises on allocators, errors, comptime, generics, C interop and testing, with hints, worked solutions, review questions and ideas for bigger projects.