zig
Zig v0.17.021sections125entries182code samples67tables28runnable

The Zig Cheatsheet

A dense, one-page reference for the Zig programming language — syntax, stdlib, allocators, comptime and more, with examples aligned to ziglings. Press ⌘K to search.

Start reading

Section 1 of 21: Getting Started

7 entries

Install Zig, write your first program, master the CLI.

#001

Install & Verify

One static binary, no package manager, nothing else to configure.

Grab a build for your platform from ziglang.org/download. Zig ships as a single ~45 MB static binary — no runtime, no VM, no dependencies. Unpack it, put it on your PATH, done.

Verify the install
zig version# 0.17.0
  • Also available via brew install zig / apt install zig — but package-manager versions often lag behind the latest release.
  • Upgrading is just replacing the folder; projects live in your own directories, not in the toolchain.
#002

Hello, World! (0.16)

since 0.16ziglings 001–002

The canonical 0.16 main signature comes with an allocator, I/O handle and CLI args.

hello.zig
const std = @import("std");pub fn main(init: std.process.Init) !void {    try std.Io.File.stdout().writeStreamingAll(init.io, "Hello, world!\n");}
verified · zig 0.17.0

The 0.16 Juicy Main signature: init bundles init.gpa, init.io, init.arena plus CLI args and environment.

  • std.debug.print("Hello!\n", .{}) writes to stderr and works with any main signature — ideal for quick prints.
  • An empty pub fn main() !void is still legal — but then you get no access to CLI args or environment.
  • std.process.Init.Minimal provides only args + environ, skipping the rest of the I/O setup.
Compile and run in one step
zig run hello.zig
#003

Zig CLI

One tool compiles, tests, formats, cross-compiles — and even builds C code.

CommandWhat it does
zig run file.zigCompile and run immediately
zig build-exe / -lib / -objOne-shot compile to executable, library or object file
zig test file.zigBuild and run every test block
zig fmt .Canonical formatter — no config, no debates
zig buildProject build system driven by build.zig
zig initScaffold a new project (build.zig + src/main.zig)
zig fetch <url>Fetch and cache a package dependency
zig cc / zig c++Drop-in C/C++ compiler with free cross-compilation
zig translate-c file.cConvert C source to Zig
zig env / zig targetsShow cache/lib paths / list supported compile targets
FlagEffect
-O Debug|ReleaseSafe|ReleaseFast|ReleaseSmallChoose the build mode (see below)
-target x86_64-linux-muslCross-compile for any arch-os-abi
-mcpu <name>Select target CPU and feature set
FlagEffect
-O debug|safe|fast|smallChoose the build mode (see below)
-target x86_64-linux-muslCross-compile for any arch-os-abi
-mcpu <name>Select target CPU and feature set

Mode naming is one-way: 0.17 takes debug / safe / fast / small and still accepts Debug / ReleaseSafe / ReleaseFast / ReleaseSmall — deprecated aliases on 0.17, not removals. The short names are the compile fact: zig build-exe main.zig -O safe stops on 0.16 with unrecognized optimization mode: 'safe'.

Cross-compile a static binary — no extra toolchain
zig build-exe main.zig -O ReleaseFast -target x86_64-linux-musl./main

0.16 spells the modes Debug / ReleaseSafe / ReleaseFast / ReleaseSmall. The 0.17 short name is rejected here: error: unrecognized optimization mode: 'fast'.

Cross-compile a static binary — no extra toolchain
zig build-exe main.zig -O fast -target x86_64-linux-musl./main

0.17 takes the short mode names. The -O ReleaseFast line in the 0.16 tab still compiles on 0.17 — a deprecated alias, so this tab is curation, not a break. The short names do not work on 0.16.

CommandWhat it doeson 0.16
zig fmt --complexity file.zigToken and node count per file, plus a totalunrecognized parameter: '--complexity'
zig cache-cat .zig-cache/h/<hash>Print a build-cache manifest as ZONno such command — prints the usage list
Complexity report — real output
zig fmt --complexity main.ziginfo: main.zig: tokens=52 nodes=25info: total: tokens=52 nodes=25

Measured on this box with Zig 0.17.0. Useful before blaming a slow compile on the code: tokens and nodes grow with nesting, and a file with a huge node count is a file the compiler has to think about.

#004

What Ships In The Box

Every Zig release carries its own Clang and its own libc version table. Both moved between 0.16 and 0.17.

Bundled piece0.16.00.17.0
Clang behind zig cc / zig c++21.1.022.1.8
Highest glibc zig targets knows2.43.02.44.0 — target it with -target x86_64-linux-gnu.2.44
Read the stamp off your own install
zig cc --version | head -1zig targets | grep -o '"2.[0-9]*.0"' | tail -1

Do not trust a blog post for these two numbers — including this page. Both lines are one command, and they answer for the install you have.

The Clang major version is the LLVM major version: zig cc --version reporting 22.1.8 means Zig 0.17.0 ships LLVM 22. Cross-compiling to a glibc newer than the table above fails — the table is the list of libc versions Zig knows how to link against.

What this page does not claim:Release notes also list musl, Linux kernel headers and macOS SDK bumps. They are not published here, because nothing on this box measures them — zig targets exposes the glibc table and nothing else. Check your own install before planning a cross-compile against them.
#005

Build Modes

Four modes trade compile time, runtime speed, size and safety checks.

ModeCompile timeRuntimeSafety checksNotes
DebugfastestslowestallDefault for zig run, zig test
ReleaseSafesloweroptimizedallPanics on overflow, out-of-bounds, …
ReleaseFastslowerfastestoffViolations become undefined behaviour
ReleaseSmallslowersmall, less optimizedmostly offOptimizes for binary size
ModeCompile timeRuntimeSafety checksNotes
debugfastestslowestallDefault for zig run, zig test
safesloweroptimizedallPanics on overflow, out-of-bounds, …
fastslowerfastestoffViolations become undefined behaviour
smallslowersmall, less optimizedmostly offOptimizes for binary size

0.17 renamed the modes: debug, safe, fast, small. The Debug / ReleaseSafe / ReleaseFast / ReleaseSmall spellings keep compiling on 0.17 as deprecated aliases — the behaviour in every column is identical in both views, only the name moved. The short names are the one-way fact: 0.16 stops with error: unrecognized optimization mode.

ReleaseFast removes the guard rails:In ReleaseFast, integer overflow or an out-of-bounds access is undefined behaviour — it may silently corrupt memory instead of panicking. Ship ReleaseSafe unless you truly need the last few percent of performance.
fast removes the guard rails:In fast — the 0.17 name for ReleaseFast — integer overflow or an out-of-bounds access is undefined behaviour: it may silently corrupt memory instead of panicking. Ship safe unless you truly need the last few percent of performance.
Typical workflow
zig run app.zig                     # iterate in Debugzig test app.zig                    # tests in Debugzig build-exe app.zig -O ReleaseSafe  # ship with safety checkszig build -Doptimize=ReleaseFast      # via build.zig
Typical workflow
zig run app.zig                 # iterate in debugzig test app.zig                # tests in debugzig build-exe app.zig -O safe    # ship with safety checkszig build -Doptimize=fast       # via build.zig

The ReleaseSafe / ReleaseFast lines in the 0.16 tab still run on 0.17 unchanged — deprecated aliases. -O safe is the 0.17-only spelling: 0.16 rejects it with unrecognized optimization mode: 'safe'.

#006

Comments & Docs

Line comments only — plus two flavours of doc comments for autodoc.

zig
//! Top-level doc comment: describes the whole FILE./// Doc comment for the declaration that follows./// Rendered by zig build-docs / autodoc.pub fn add(a: i32, b: i32) i32 {    return a + b; // plain line comment}// There are no /* block comments */ in Zig.
  • // — the only comment. There are no block comments.
  • /// — doc comment; attaches to the declaration below it and shows up in generated docs.
  • //! — file-level doc comment; must appear at the very top of the file.
#007

File Anatomy & Imports

Every file is a namespace; @import wires them together; pub controls visibility.

  • @import("std") resolves to the standard library; @import("math.zig") loads a file relative to the current file.
  • pub makes a declaration visible to importers — everything else stays private to the file.
  • Declaration order is irrelevant: top-level decls are lazily analyzed, so forward references just work.
  • Every file is implicitly a struct / namespace; @This() names it from inside.
  • The entry point lives in the root source file — main.zig when you zig run main.zig, or the root module declared in build.zig.
main.zig
const std = @import("std");const math = @import("math.zig");pub fn main() !void {    const sum = math.add(2, 3);    std.debug.print("{d}\n", .{sum});}
math.zig
const magic = 42; // private to this filepub fn add(a: i32, b: i32) i32 {    return a + b;}// Order never matters:pub const two = add(1, 1);

Non-pub decls like magic are invisible to importers — the file boundary is a hard visibility wall.

Section 2 of 21: Language Basics

6 entries

const vs var, statements vs expressions, labeled blocks, undefined and the comptime mindset.

#008

Variables: const & var

ziglings 003, 051

Two keywords, strict usage rules, and compile errors that keep code honest.

const is immutable, var is mutable. Types are usually inferred; write them when it matters: const x: u32 = 1;.

zig
const answer: u32 = 42;      // immutable, explicit typevar counter = answer;        // mutable, type inferred (u32)counter += 1;                // ok: vars may be reassignedfn sum(items: []const u32) u32 {    var total: u32 = 0;    for (items) |item| total += item;    return total;}
FormMeaning
const x = v;Immutable binding
var x = v;Mutable binding
_ = x;Explicitly discard — silences the unused error
_ = &x;Take and discard the address — also counts as a use
Compile errors you will hit on day one:Unused local variables and parameters are errors — discard them with _ = x;. A var that is never mutated is an error. So is shadowing an identifier from an outer scope.
#009

Statements ≠ Expressions

Assignment is a void statement; control flow yields values instead.

Zig separates the two strictly: assignment returns void, so x = y = 0 is impossible. There is no ++ / -- (use x += 1) and no ternary — because if is an expression.

zig
const a = 3;const b = 7;// const c = a = b;            // ERROR: assignment yields void// a++;                        // ERROR: no ++ — use a += 1// const max = a > b ? a : b;  // ERROR: no ternary operatorconst max = if (a > b) a else b;         // 7const ok = (a < b) and (b != 0);         // and / or / ! — never && || !const both = blk: {                      // blocks are expressions too    const squared = a * a;    break :blk squared + b;              // yields 16};
#010

Blocks & Scope

Labeled blocks are inline scopes that can yield a value.

Declarations live inside their block's scope. Any block can be given a label; break :label value; exits it with a result — Zig's tool for computed fallback chains and early exits from a scope.

zig
const n: i32 = -4;const magnitude = abs: {    if (n >= 0) break :abs n;   // leave early with a value    break :abs -n;};                              // magnitude == 4// Reads like an inline function:const squares = first_three: {    var buf: [3]u32 = undefined;    for (0..3) |i| buf[i] = @intCast((i + 1) * (i + 1));    break :first_three buf;};

Labeled blocks replace many nested-if and switch-fallback patterns — and pair naturally with errdefer-style control flow later on.

#011

undefined

ziglings 050

Opt out of initialization — the 0xAA fill and the compiler both have opinions.

var x: u32 = undefined; means no initialization. In Debug and ReleaseSafe the bytes are filled with 0xAA so stale reads are obvious; in the other modes they are garbage. Useful for deferred init and buffers you will fully overwrite.

zig
var buf: [64]u8 = undefined;   // uninit 64 bytesbuf[0] = 'H';buf[1] = 'i';var total: u32 = undefined;    // deferred inittotal = 10;total += 5;                    // safe: written before any read
undefined is not a value:Reading a location that was never written is undefined behaviour — the 0xAA fill is a debugging aid, not a check. undefined may only initialize a var; a const needs a real value.
#012

The comptime Keyword

Anything can run at compile time — that is how Zig does generics.

Zig has no macros and no template engine: the language itself is the metaprogramming layer. comptime marks parameters, variables or blocks that must be known at compile time — and types themselves are values of type type.

zig
fn Buffer(comptime T: type, comptime size: usize) type {    return struct {        items: [size]T,        len: usize = 0,    };}const Buf8 = Buffer(u8, 8);     // a brand-new type...const Buf32 = Buffer(u8, 32);   // ...generated at compile timeconst n = 40 + 2;               // comptime_int: arbitrary-precision math
  • comptime_int grows arbitrarily — integer literals have no fixed width until assigned to a typed const / var.
  • Every instantiation compiles fresh code, including whatever parts of std it touches — that is why the whole std library feels like it is compiled per-use.
  • This is Zig's answer to C macros and C++ templates: ordinary code, evaluated at compile time.
Run it: complete program
const std = @import("std");pub fn main() void {    const x = 3; // comptime_int — no machine type yet    const y: f32 = 3; // forced to f32    std.debug.print("{s} {s}\n", .{ @typeName(@TypeOf(x)), @typeName(@TypeOf(y)) });}
verified · zig 0.17.0
#013

Identifiers & Literals

ziglings 079

snake_case, raw identifiers for keywords, and every numeric literal prefix.

zig
const max_value = 1_000_000;     // snake_case — zig fmt enforces the styleconst flags = 0b1010;            // binaryconst perms = 0o755;             // octalconst mask = 0xFF;               // hexconst big = 1_000.5;             // _ works in floats tooconst letter = 'a';              // char literal (comptime_int)const newline = '\n';const emoji: u21 = '\u{1F600}'; // unicode code pointconst @"if" = 1;                 // raw identifier for keywords...const @"weird name" = 2;         // ...or any unusual spelling
LiteralKind
123, 1_000_000Decimal integer, _ as separator
0b1010, 0o755, 0xFFBinary / octal / hex integer
1_000.5, 1e10Float
'a', '\n', '\u{1F600}'Character — a comptime_int
@"if"Raw identifier — escapes keywords and spaces

Section 3 of 21: Primitive Types

6 entries

Integers of any width, IEEE floats, bool / void / noreturn — and exactly which values coerce.

#014

Integers

ziglings 059

Any bit width you want, plus the special arbitrary-precision comptime_int.

TypeNotes
u8 i8 u16 i16 u32 i32 u64 i64 u128 i128The fixed-width family
usize / isizePointer-sized; required for indexing
u7, i47, u65535Arbitrary widths — any uN / iN with N ≤ 65535
u0Zero-bit type; its only value is 0
comptime_intArbitrary precision — the default type of integer literals
zig
const a: u8 = 255;             // fits exactlyconst b = 300;                 // comptime_int — no width yetconst c: u16 = b;              // ok: 300 fits u16// const d: u8 = b;            // compile error: 300 does not fit u8const e: u9 = 511;             // odd widths are fineconst byte = 'A';              // char literal coerces into u8 and friends
#015

Overflow Behavior

Panics, UB or wraps — plus wrapping and saturating operator variants.

Build modeOn overflow
Debug / ReleaseSafePanic (safety-checked)
ReleaseFastUndefined behaviour
ReleaseSmallWraps (well-defined)
Build modeOn overflow
debug / safePanic (safety-checked)
fastUndefined behaviour
smallWraps (well-defined)

Same three behaviours, two spellings: 0.17 renamed the modes to debug / safe / fast / small. ReleaseSafe, ReleaseFast and ReleaseSmall still compile on 0.17 as deprecated aliases, so nothing about overflow behaviour changed between the views. The short names are 0.17-only — 0.16 stops with error: unrecognized optimization mode.

ToolMeaning
+% -% *%Wrapping add / sub / mul
+| -| *|Saturating add / sub / mul
<<|Saturating shift left
@addWithOverflow(a, b)Returns a tuple: result + overflow bit
zig
const big: u8 = 250;const wrapped = big +% 10;          // 4const saturated = big +| 10;        // 255const shifted = @as(u8, 1) <<| 9;   // 255 — saturates instead of UBconst pair = @addWithOverflow(big, @as(u8, 10));// pair[0] == 4, pair[1] == 1 (overflowed)
#016

Floats

ziglings 060

IEEE floats up to 128 bits — conversions stay explicit.

TypeNotes
f16 f32 f64 f80 f128IEEE-754 widths; hardware support varies
comptime_floatThe type of float literals at compile time

Integers and floats never mix implicitly in arithmetic: 1 + x with x: f32 is an error — write @as(f32, 1) + x. Convert explicitly with @floatFromInt, @intFromFloat (out-of-range is undefined behaviour; safety-checked panic in safe modes) and @floatCast. There is no NaN literal — use std.math.nan(f64).

zig
const std = @import("std");const pi: f64 = 3.14159;const root = @sqrt(pi);                 // runtime and comptimeconst smaller: f32 = @floatCast(pi);    // f64 -> f32const n: i32 = @intFromFloat(3.99);     // truncates toward zero: 3const f: f64 = @floatFromInt(7);        // 7.0const not_a_number = std.math.nan(f64);
0.16: small integers now coerce into floats:Since 0.16, small integer widths coerce into larger float types (e.g. u8 into f64) where every value is exactly representable — no cast needed.
#017

bool, void & noreturn

Three tiny types that shape control flow.

zig
const std = @import("std");const ready: bool = true;const check = ready and !ready;   // and / or / ! onlyconst unit: void = {};            // zero-bit: takes no memoryfn log(msg: []const u8) void {    std.debug.print("{s}\n", .{msg});}fn crash() noreturn {             // never returns    unreachable;                  // panics — or: while (true) {}}
  • bool — true / false, combined with the and / or / ! keywords.
  • void — the unit type; its only value is {}. Zero-bit types (void, u0, empty structs) occupy no memory.
  • noreturn — the type of unreachable, panics and infinite loops without break; useful as a return type and in else prongs.
#018

Implicit Coercions

ziglings 061

Widening is free; narrowing must be explicit and runtime-checked.

FromToImplicit?
u8u32 (wider, same sign)yes
u32u8 (narrower)no — @intCast
i32u64 (sign change)no — signs must match
[N]T[]const Tyes
string literal *const [N:0]u8[]const u8 / [*:0]const u8 / *const [N]u8yes
*T?*Tyes (same size)
T?Tyes
TE!Tyes
error setsuperset error setyes
comptime_int / comptime_floatany int / float that fitsyes
Narrowing never happens silently:const small: u8 = big; with big: u32 is a compile error. Make it explicit with @intCast(big) — runtime-checked, panics in safe modes when the value does not fit (undefined behaviour in ReleaseFast, called fast on 0.17).
#019

Type Reflection

Introspect any type at compile time via @typeInfo.

Type reflection — 0.16 spelling
const std = @import("std");const T = @TypeOf(42);             // comptime_intconst label = @typeName(u32);      // "u32"const size = @sizeOf(u64);         // 8 — also @bitSizeOf / @alignOfconst S = struct { id: u32, name: []const u8 };const info = @typeInfo(S);const fields = info.@"struct".fields;   // keyword tags need @"" quoting// Printing is runtime work — std.debug.print does not run inside a comptime block.inline for (fields) |f| {    std.debug.print("{s}: {s}\n", .{ f.name, @typeName(f.type) });   // id: u32, name: []const u8}

0.16 hands back a fields list of StructFields: .name, .type, .default_value_ptr, .is_comptime, .alignment. Printing at comptime is not a thing — comptime { std.debug.print(...) } fails on 0.16 and 0.17 alike with unable to resolve comptime value from std/Io/Threaded.zig. inline for is required: a plain for over fields fails with values of type 'builtin.Type.StructField' must be comptime-known, but index value is runtime-known.

Type reflection — 0.17 spelling
const std = @import("std");const T = @TypeOf(42);             // comptime_intconst label = @typeName(u32);      // "u32"const size = @sizeOf(u64);         // 8 — also @bitSizeOf / @alignOfconst S = struct { id: u32, name: []const u8 };const info = @typeInfo(S);const names = info.@"struct".field_names;   // 0.17: no fields list at allconst types = info.@"struct".field_types;   // parallel slice, same order// Printing is runtime work — std.debug.print does not run inside a comptime block.inline for (names, types) |name, field_type| {    std.debug.print("{s}: {s}\n", .{ name, @typeName(field_type) });   // id: u32, name: []const u8}

0.17 dropped the field list: @typeInfo(T).@"struct".fields now fails with no field named "fields" in struct lang.Type.Struct, and 0.16 rejects the new form with no field named 'field_names' in struct 'builtin.Type.Struct'. Field facts arrive as parallel slices — field_names, field_types, field_attrs.

  • @typeInfo(T) returns a tagged union; tags are lowercase snake_case: .int, .pointer, .@"struct", …
  • 0.16: each struct field is a StructField exposing .name, .type, .default_value_ptr (read it with defaultValue()), .is_comptime and .alignment.
  • 0.17: there is no field list. @typeInfo(T).@"struct" gives parallel slices field_names, field_types, field_attrs (plus decl_names); read a default as attrs[i].defaultValue(types[i]).
  • Iterating fields needs inline for — a plain for fails with "values of type ... must be comptime-known, but index value is runtime-known", on both compilers.
  • comptime { std.debug.print(...) } fails on both compilers — printing is runtime work.
  • 0.16: @Type was removed — build types with individual builtins instead: @Struct, @Enum, @Pointer, @Array, …

Section 4 of 21: Arrays, Slices & Strings

7 entries

Fixed arrays, runtime slices, UTF-8 byte strings, sentinel terminators and SIMD vectors.

#020

Arrays

ziglings 004–005

Fixed length, comptime-known, value semantics.

zig
const std = @import("std");const fixed = [3]u8{ 1, 2, 3 };const inferred = [_]u8{ 4, 5, 6 };     // length from the initializerconst filled: [16]u8 = @splat(0xAA);    // @splat fills every elementconst grid = [2][3]u8{    .{ 1, 2, 3 },                      // nested arrays    .{ 4, 5, 6 },};for (inferred) |item| std.debug.print("{d}\n", .{item});for (fixed, 0..) |item, i| std.debug.print("[{d}]={d}\n", .{ i, item });
Array repetition — 0.16 only
const filled = [1]u8{ 0xAA } ** 16;   // 0.16: repeat one element 16 timesconst zeros = [_]u8{ 0 } ** 4;        // length inferred, then repeated

0.17 removed array repetition. ** is not an operator any more, so the 0.17 compiler rejects both lines — @splat is the replacement above.

  • [N]T — the length is part of the type and comptime-known; fixed.len is a compile-time constant.
  • Arrays are values: assignment copies, and passing to a function copies.
  • for (arr) |item| iterates values; for (arr, 0..) |item, i| adds an index.
  • Repeating an element: @splat(value) on 0.17; the old [N]T{v} ** n form is gone — switch to the 0.16 tab to see it.
#021

Slices

ziglings 052–053

A pointer plus runtime length — the workhorse view type.

zig
var data = [_]u32{ 1, 2, 3, 4, 5 };const window: []u32 = data[1..4];      // { 2, 3, 4 }const rest = data[2..];                // open-ended: to the endconst whole: []const u32 = &data;      // [N]T coerces to []const Tfn sum(items: []const u32) u32 {    var total: u32 = 0;    for (items) |item| total += item;  // len lives at runtime    return total;}
Slice → array — 0.17
const std = @import("std");

pub fn main() !void {
    const list = [_]u16{ 1, 2, 3 };
    const slice: []const u16 = &list;

    const arr: [3]u16 = slice.*;        // slice -> array copy
    const ptr: *const [3]u16 = slice;   // slice -> array pointer, no copy

    std.debug.print("arr={any} ptr={any}\n", .{ arr, ptr.* });
}
verified · zig 0.17.0

COMPILE FACT: 0.16 answers index syntax required for slice type '[]const u16'. The length must be comptime-known — a slice built at runtime with a variable length cannot be coerced, because [N]T needs N at compile time.

  • []T is a mutable view, []const T read-only. A slice is a **pointer + runtime .len**; slice.ptr hands out the raw pointer.
  • Slicing a slice works: rest[1..2]. Bounds are checked at runtime — out of range panics in safe modes.
  • Multi-object loop: for (as, bs) |a, b| iterates two sequences in lockstep — equal lengths are a runtime-checked requirement.
  • 0.17 only: a slice with a comptime-known length coerces to an array — slice.* copies, *const [N]T points. 0.16 has no such coercion.
#022

Strings

ziglings 006–007

No string type — just []const u8 over UTF-8 bytes.

A string literal has type *const [N:0]u8 (null-terminated at compile time). The canonical string type is []const u8 — a byte slice, not null-terminated, holding arbitrary UTF-8. There is no built-in string type and no concat operator: build strings with an allocator.

zig
const std = @import("std");const literal = "héllo";                       // *const [6:0]u8const view: []const u8 = literal;              // canonical string typeconst same = std.mem.eql(u8, "abc", "abc");    // byte compare: trueconst starts = std.mem.startsWith(u8, "hello!", "hell");const valid = std.unicode.utf8ValidateSlice("héllo");// Iterate codepoints:var it = std.unicode.Utf8View.initUnchecked("héllo").iterator();while (it.nextCodepoint()) |cp| { _ = cp; }
Concatenation needs an allocator
pub fn main(init: std.process.Init) !void {    const greeting = try std.fmt.allocPrint(init.arena.allocator(), "hi, {s}!", .{"zig"});    try std.Io.File.stdout().writeStreamingAll(init.io, greeting);}

0.16 formats through the std.fmt namespace, passing the allocator as the first argument. This still compiles on 0.17 — it is just not the spelling to write any more.

Formatting on 0.17: the allocator does it
pub fn main(init: std.process.Init) !void {    const greeting = try init.arena.allocator().print("hi, {s}!", .{"zig"});    try std.Io.File.stdout().writeStreamingAll(init.io, greeting);}
verified · zig 0.17.0

On 0.17 print is a method on mem.Allocator — no namespace, no allocator argument. This is a compile break in the other direction: 0.16 answers no field or member function named 'print' in 'mem.Allocator'.

ExpressionType / result
"hi"*const [2:0]u8
"hi" coerced[]const u8, [*:0]const u8, *const [2]u8
'x'Char literal — a comptime_int
std.mem.concat(alloc, u8, .{a, b})New heap buffer from parts
#023

Multiline String Literals

Every line starts with \\ — no escapes, ever.

zig
const css =    \\body {    \\  color: red;    \\} /* end */;
  • Each line starts with \\; line breaks and spacing are preserved exactly.
  • No escape sequences inside — \\n is a literal backslash followed by n.
  • The final line contributes no trailing newline.
  • The declaration's ; sits on its own line after the last \\ line — inside a \\ line it is literal text.
#024

Sentinel-Terminated

ziglings 076–078

Terminators baked into the type — how Zig talks to C.

zig
const std = @import("std");const c_str: [*:0]const u8 = "hello";   // many-item + terminatorvar buf: [16:0]u8 = undefined;          // array with a slot for the 0buf[0] = 'o';buf[1] = 'k';buf[2] = 0;const s: [:0]u8 = buf[0..2 :0];         // slice that keeps the sentinelconst span: []const u8 = std.mem.span(c_str);   // scan to terminator
  • [N:0]u8 — sentinel-terminated array; [:0]u8 — slice whose memory past the end is the sentinel value.
  • std.mem.span / std.mem.spanZ turn a [*:0]u8 into a length-aware slice — the bridge from C strings.
  • allocator.allocSentinel(u8, n, 0) allocates a sentinel-terminated buffer.
  • Common uses: C interop (char *), in-place formatting buffers.
Run it: complete program
const std = @import("std");pub fn main() void {    const s: [:0]const u8 = "sentinel";    // One past the last byte is the sentinel, and it is readable.    std.debug.print("{d} {d}\n", .{ s.len, s[s.len] });}
verified · zig 0.17.0
#025

Vectors (SIMD)

ziglings 109

Fixed-width SIMD lanes with element-wise operators.

zig
const a: @Vector(4, f32) = .{ 1.0, 2.0, 3.0, 4.0 };const b: @Vector(4, f32) = @splat(2.0);     // broadcast to every laneconst sum = a + b;                 // element-wise: { 3, 4, 5, 6 }const total = @reduce(.Add, sum);  // horizontal: 18.0const pick = @select(f32, a > b, a, b);   // per-lane max here
  • @Vector(len, T) — the length must be comptime-known; lanes are bool, integer or float.
  • Operators apply element-wise; @reduce collapses to a scalar; @select picks per lane; std.simd has extra helpers.
  • @splat(scalar) broadcasts a scalar to every lane — the vector's type sets the length.
0.16: arrays and vectors no longer coerce in memory:Since 0.16, [4]f32 and @Vector(4, f32) are kept strictly apart — convert between them explicitly with @bitCast.
#026

Compile-Time Data: @embedFile

Bake files into the binary as comptime-known bytes.

zig
const std = @import("std");const logo = @embedFile("assets/logo.svg"); // *const [N:0]u8const size: usize = logo.len; // comptime-knownpub fn main(init: std.process.Init) !void {    const msg = try std.fmt.allocPrint(init.arena.allocator(), "embedded {d} bytes\n", .{size});    try std.Io.File.stdout().writeStreamingAll(init.io, msg);}
Same embed, 0.17 formatting
const std = @import("std");const logo = @embedFile("assets/logo.svg"); // *const [N:0]u8const size: usize = logo.len; // comptime-knownpub fn main(init: std.process.Init) !void {    const msg = try init.arena.allocator().print("embedded {d} bytes\n", .{size});    try std.Io.File.stdout().writeStreamingAll(init.io, msg);}
verified · zig 0.17.0
  • The path is relative to the source file and must stay inside the module — the file becomes part of your binary.
  • Result type is *const [N:0]u8: a comptime-known, sentinel-terminated byte array.
  • For runtime files, use the file-system APIs (std.fs, Io.Dir) instead.
  • Works naturally with zig build modules — assets can also come from dependency packages.

Section 5 of 21: Pointers

6 entries

Six pointer spellings, manual arithmetic, casts and alignment discipline — non-null unless you ask.

#027

Taking Addresses

ziglings 039–040

& to take, .* to dereference — parameters are always values.

zig
var score: u32 = 100;const p: *u32 = &score;        // pointer to scorep.* += 10;                     // deref-write: score == 110const q: *const u32 = &score;  // read-only pointerconst v = q.*;                 // deref-read: 110fn bump(n: *u32) void {        // to mutate the caller's value,    n.* += 1;                  // take a pointer parameter}bump(&score);                  // score == 111

Everything is passed by value and parameters are immutable — there is no implicit by-reference. To mutate a caller's value (or avoid copying a big struct) pass a *T; pass *const T for read-only access.

#028

Pointer Kinds

ziglings 041–044

Six pointer spellings — size, length and nullability differ.

TypePoints toLengthNullableNotes
*Tone item1noNon-null, naturally aligned
*const Tone item1noPointee is read-only
[*]Tmany itemsunknownnoNo .len — arithmetic allowed
[*:0]Tmany itemssentinel-delimitednoC-string style
[]T / []const Tmany itemsruntime .lennoSlice: pointer + length
[*c]Tmany or oneunknownyesC pointer from translate-c; coerces both ways
?*Tone item1yesSame size as *T — null reuses the zero bits

A non-optional pointer can never be null, and ?*T costs no extra memory — Zig reserves the all-zero-bits pattern as null. Prefer slices over bare pointers whenever a length is meaningful.

#029

Pointer Arithmetic

ziglings 054

Reserved for many-item pointers — slices lend you their .ptr.

zig
var data = [_]u32{ 10, 20, 30, 40 };const p: [*]u32 = &data;      // many-item pointerconst second = p + 1;         // arithmetic: only on [*]Tsecond[0] = 99;               // data[1] == 99 — no bounds checkconst slice: []u32 = data[0..4];const base = slice.ptr;       // same [*]u32const addr: usize = @intFromPtr(base);const back: [*]u32 = @ptrFromInt(addr);
Manual and unguarded:[*]T has no length, so indexing it skips bounds checks. In most code, slicing (p[0..n]) or keeping a []T is the safer — and equally fast — choice.
#030

Pointer Casts

One builtin per job — and alignment is your responsibility.

zig
var bytes = [_]u8{ 0x37, 0x13, 0x00, 0x00 };// Reinterpret the pointee type — here with lowered alignment:const loose: *align(1) const u32 = @ptrCast(&bytes);// Raise alignment: you must guarantee it is truly aligned:const strict: *const u32 = @alignCast(loose);const frozen: []const u8 = &bytes;const thawed: []u8 = @constCast(frozen);   // remove const
BuiltinJob
@ptrCastChange pointee type / pointer width — may only *lower* alignment
@alignCastRaise the alignment — UB if the real alignment is lower
@constCastRemove const from a pointer
@volatileCastRemove volatile from a pointer
Alignment UB:Casting a pointer to a higher alignment than the data actually has is undefined behaviour — misaligned loads can fault or silently corrupt. @alignCast is a promise, not a check.

0.16: explicitly aligned pointer types like *align(1) u32 are now distinct types from the naturally aligned *u32 — but they still coerce to each other.

#031

volatile & allowzero

Talking to hardware and the zero address.

zig
const status_reg: *volatile u32 = @ptrFromInt(0x4000_0000);// Reads are never elided or reordered away:while ((status_reg.* & 1) == 0) {}   // wait for the ready bit// Writes are never removed:status_reg.* = 0x1;
  • *volatile T marks accesses as observable — required for memory-mapped I/O and any other storage the compiler cannot see.
  • *allowzero T permits address 0 as a valid pointer value (rare; needed only for special ABIs).
  • @prefetch(ptr, .{}) hints the cache without dereferencing.
#032

Pointer Metadata & Slice Patterns

Inspect pointer types at comptime; turn buffers into slices early.

zig
var buf: [64]u8 = undefined;const n = 10;const view: []u8 = buf[0..n];    // buffer + count -> slice: the idiomconst info = @typeInfo([]const u8).pointer;// info.size      -> enum: .one / .many / .slice / .c// info.is_const  -> bool// info.alignment -> comptime_int// info.child     -> u8// info.sentinel  -> ?u8 (for sentinel pointers)

The golden rule: a raw buffer plus a count should become a slice (buf[0..n]) as early as possible — slices carry their length, work with for, and keep bounds checks.

Section 6 of 21: Structs

6 entries

Plain data with namespaces: methods, tuples, destructuring, packed bits and extern layouts.

#033

Declaring & Initializing

ziglings 037–038

Fields, defaults and decl-literal initialization.

zig
const Point = struct {    x: f64 = 0,               // default value    y: f64 = 0,    const origin = Point{ .x = 0, .y = 0 };   // container-level decl};const a: Point = .{ .x = 1, .y = 2 };   // decl-literal initconst b = Point{ .y = 5 };              // full form; x takes the defaultconst c = a;                            // copy — structs are values
  • Fields may have defaults; omitted fields use them.
  • .{ ... } is the anonymous init (a decl literal) — it needs a result type; Point{ ... } is the explicit form.
  • Structs are plain values: assignment and parameter passing copy. No inheritance, no constructors — just data plus functions.
#034

Methods & Namespaces

ziglings 047–048

Functions inside a struct — with an explicit self, no magic.

zig
const Vec = struct {    x: f64,    y: f64,    fn length(self: Vec) f64 {           // by value: read-only use        return @sqrt(self.x * self.x + self.y * self.y);    }    fn scale(self: *Vec, k: f64) void {  // by pointer: mutation        self.x *= k;        self.y *= k;    }};var v = Vec{ .x = 3, .y = 4 };const len = v.length();      // sugar for Vec.length(v)v.scale(2);                  // sugar for Vec.scale(&v, 2)
  • There is **no implicit this**: the first parameter is the receiver, conventionally named self (Vec, *Vec or *const Vec).
  • Method-call syntax v.scale(2) is sugar — it auto-takes &v when the receiver is a pointer.
  • Non-method fns and consts in the body act as static members; @This() names the struct itself from inside.
#035

Tuples & Anonymous Structs

ziglings 080–083

Struct literals without a name, plus 0.14 destructuring.

zig
const pair = .{ 3, 7 };                 // tuple: fields "0", "1"const point = .{ .x = 1, .y = 2 };      // anonymous structconst mixed = .{ 1, "two", true };      // heterogeneous tupleconst first = mixed[0];                 // comptime index// Destructuring is a statement, so it lives in a block (0.14+):const demo = d: {    const lo, const hi = pair;          // tuple fields, by position    const px, const py = point;         // struct fields, in order    var a: u32 = 1;    var b: u32 = 2;    a, b = .{ b, a };                   // SEQUENTIAL: a=2, then b=a=2 — not a swap    var x: u32 = 1;    var y: u32 = 2;    std.mem.swap(u32, &x, &y);          // the real swap: x=2, y=1    break :d .{ lo, hi, px, py, a, b, x, y };};
  • .{ 1, 2 } is a tuple (fields named "0", "1", …); .{ .a = 1 } is an anonymous struct. Both are real struct types.
  • Destructuring since 0.14: const a, const b = tup; — a statement, so it lives inside a block; var variants work too.
  • Multi-assign a, b = .{ b, a }; is sequential, not simultaneous — it leaves a=2, b=2. Swap with std.mem.swap(T, &a, &b).
  • Tuples power multi-object loops: for (as, bs) |a, b| iterates a tuple of slices.
  • Without destructuring, a swap needs a temp: const tmp = a; a = b; b = tmp;.
#036

Packed Structs

Exact bit layout over a backing integer.

zig
const Flags = packed struct(u16) {    visible: bool,      // 1 bit    layer: u8,          // 8 bits    tag: u7,            // 7 bits};                      // 1 + 8 + 7 == 16, no paddingconst f = Flags{ .visible = true, .layer = 3, .tag = 127 };const bits: u16 = @bitCast(f);       // to the backing integerconst back: Flags = @bitCast(bits);  // and back
@bitCast from an extern struct — 0.16 only
const E = extern struct { lo: u16, hi: u16 };const s = E{ .lo = 1, .hi = 2 };const bits: u32 = @bitCast(s);   // 0.16: fine. 0.17: cannot @bitCast from 'E'
The route that works on both
const E = extern struct { lo: u16, hi: u16 };const s = E{ .lo = 1, .hi = 2 };const p: *align(1) const u32 = @ptrCast(&s);   // reinterpret through a pointerconst bits: u32 = p.*;

Reinterpretation through an aligned pointer compiles on 0.16 and 0.17 — the safe spelling to adopt now. align(1) matters: the integer view is not naturally aligned to the struct's alignment.

  • packed struct(uN) lays fields out bit-exactly over a backing integer — guaranteed in-memory layout, zero padding.
  • Field widths must add up exactly; convert with @bitCast.
  • 0.16: pointers are not allowed inside packed structs and packed unions.

0.16: packed structs and packed unions can now appear directly as switch prong items.

#037

extern Structs

C-compatible layout for FFI boundaries.

zig
const Header = extern struct {    magic: u32,          // field order is guaranteed    width: u32,    height: u32,    data: [*]const u8,   // pointers are fine};
KindLayoutUse for
structCompiler's choice — may reorder and padEverything inside Zig-land
packed struct(uN)Exact bits over a backing integerWire formats, hardware registers
extern structC ABI, field order guaranteedInterop with C, syscalls, file formats
#038

Field Introspection

Access fields by name at runtime; walk them at compile time.

Field facts at comptime, printing at runtime — 0.16 spelling
const std = @import("std");const User = struct {    id: u32,    name: []const u8,};const user = User{ .id = 7, .name = "ada" };// Comptime work: type checks and layout facts, computed at compile time.const has_id = @hasField(User, "id");const name_offset = @offsetOf(User, "name");// Printing is runtime work — std.debug.print does not run inside a comptime block.std.debug.print("has id: {}\n", .{has_id});std.debug.print("offset of name: {d}\n", .{name_offset});inline for (std.meta.fields(User)) |f| {    std.debug.print("{s}\n", .{f.name});   // id, name}const picked = @field(user, "name");           // access by runtime namestd.debug.print("picked: {s}\n", .{picked});

comptime { std.debug.print(...) } is not a thing: 0.16 and 0.17 both answer unable to resolve comptime value from std/Io/Threaded.zig. Do the type checks at comptime and print at runtime. inline for is required too — a plain for over the field list fails with values of type 'builtin.Type.StructField' must be comptime-known, but index value is runtime-known.

Field introspection — 0.17 spelling
const std = @import("std");const User = struct {    id: u32,    name: []const u8,};const user = User{ .id = 7, .name = "ada" };// Comptime work: type checks and layout facts, computed at compile time.const has_id = @hasField(User, "id");const name_offset = @offsetOf(User, "name");// Printing is runtime work — std.debug.print does not run inside a comptime block.std.debug.print("has id: {}\n", .{has_id});std.debug.print("offset of name: {d}\n", .{name_offset});inline for (@typeInfo(User).@"struct".field_names) |name| {    std.debug.print("{s}\n", .{name});   // id, name}const picked = @field(user, "name");           // access by runtime namestd.debug.print("picked: {s}\n", .{picked});

0.17 replaced the field list with parallel slices: field_names, field_types, field_attrs (plus decl_names). The messages to recognize: deprecated in favor of @typeInfo from std.meta.fields, and no field named "fields" in struct lang.Type.Struct from @typeInfo(T).@"struct".fields. std.meta.fieldNames(T) is the portable name-only call **in a plain for** — it prints id / name on 0.16 and 0.17. It is NOT portable under inline for: 0.17 answers unable to resolve comptime value, because 0.17 returns a slice ([]const [:0]const u8) that inline for cannot unroll, where 0.16 returns a pointer to a fixed-size array (*const [N][:0]const u8) that it can.

  • @field(obj, "name") — access a field (or decl) when the name is only known at runtime.
  • @hasField(T, "name"), @offsetOf(T, "name"), and @fieldParentPtr for the rare parent-pointer trick.
  • 0.16: std.meta.fields(T) (or @typeInfo(T).@"struct".fields) + inline for is the workhorse for compile-time iteration.
  • 0.17: both are gone. std.meta.fields is a compileError ("deprecated in favor of @typeInfo") and @typeInfo(T).@"struct".fields no longer exists ("no field named 'fields' in struct 'lang.Type.Struct'"). The workhorse is now @typeInfo(T).@"struct".field_names with field_types — parallel slices, same order.
  • std.meta.fieldNames(T) is the portable name-only call **in a plain for** — under inline for it breaks on 0.17 with unable to resolve comptime value.
  • Iterating fields needs inline for: a plain for over the field list fails with "values of type ... must be comptime-known, but index value is runtime-known".
  • comptime { std.debug.print(...) } fails on both compilers — printing is runtime work.

Section 7 of 21: Enums & Unions

6 entries

Exhaustive tags, payload unions with compiler-tracked active fields, and packed bit views.

#039

Enums

ziglings 035–036

Tags with an optional integer backing — exhaustive by default.

Enum to int and back (0.16 spelling)
const Color = enum { red, green, blue };const Mode = enum(u8) {        // explicit tag type    off = 0,    on = 1,    auto = 255,};const n = @intFromEnum(Mode.on);     // -> u8 valueconst m: Mode = @enumFromInt(1);     // checked in safe modesfn describe(c: Color) []const u8 {    return switch (c) {              // must be exhaustive        .red => "stop",        .green => "go",        .blue => "chill",    };}

The 0.16 spelling, complete for the 0.16 compiler. On 0.17 this pair is deprecated in favour of @backingInt / @fromBackingInt — it is NOT removed: both builtins still compile on 0.17, so this is a curation split, not a compile break.

Enum to int and back (0.17 spelling)
const Color = enum { red, green, blue };const Mode = enum(u8) {        // explicit tag type    off = 0,    on = 1,    auto = 255,};const n = @backingInt(Mode.on);              // -> u8 valueconst m: Mode = @fromBackingInt(@as(u8, 1)); // ONE argument: the valuefn describe(c: Color) []const u8 {    return switch (c) {              // must be exhaustive        .red => "stop",        .green => "go",        .blue => "chill",    };}

0.17 renames the pair: @intFromEnum -> @backingInt, @enumFromInt -> @fromBackingInt. THE TRAP: @fromBackingInt takes ONE argument — the value — and the enum type comes from the expected type. @fromBackingInt(Mode, 2) is a 0.17 compile error, expected 1 argument, found 2. A bare const y = @fromBackingInt(v) fails too: @fromBackingInt must have a known result type, with the note use @as to provide explicit result type. So annotate the target (const m: Mode = ...) or wrap the value in @as. The old pair is deprecated, NOT deleted: @intFromEnum and @enumFromInt both compile on 0.17 — curation, not a compile break. zig fmt on 0.17 rewrites them for you, and it inserts a cast you did not write: @enumFromInt(1) becomes @fromBackingInt(@intCast(1)).

  • Without a backing type, the compiler picks the smallest integer that fits all tags.
  • Enums can have methods and decls, just like structs.
  • enum(u8) { a, _ } declares a non-exhaustive enum — switching one requires a _ => prong.
  • @enumFromInt with a value that has no tag is a checked panic in safe modes; UB in ReleaseFast.
  • @fromBackingInt behaves exactly like the @enumFromInt it replaces: a runtime value with no tag panics with invalid enum value in safe modes and is UB in ReleaseFast.
  • With a comptime-known value the bad tag is caught at compile time — on 0.17 and on 0.16 alike: enum 'Mode' has no tag with value '200'.
#040

Enum Literals

.red means the red tag — of whichever type the context expects.

zig
const Color = enum { red, green, blue };const Team = enum { red, blue };fn paint(c: Color) void { _ = c; }paint(.red);                       // .red coerces to Color.redconst t: Team = .red;              // ...and also to Team.red
  • An enum literal .red coerces into any enum in the expected type that has a matching tag.
  • 0.15: generalized to decl literals — .empty, .none and friends resolve to any reachable decl, e.g. var list: std.ArrayList(u8) = .empty;.
  • 0.16: decl literals may be used directly in switch prongs.
Run it: complete program (0.16)
const std = @import("std");const Kind = enum { rock, paper, scissors };pub fn main() void {    const k: Kind = .paper; // enum literal, type from the annotation    std.debug.print("{s} {d}\n", .{ @tagName(k), @intFromEnum(k) });}

Prints paper 1 on 0.16. The same source also compiles and prints paper 1 on 0.17 — @intFromEnum is deprecated there, not deleted. The 0.17 tab shows the @backingInt spelling.

Run it: complete program (0.17)
const std = @import("std");const Kind = enum { rock, paper, scissors };pub fn main() void {    const k: Kind = .paper; // enum literal, type from the annotation    std.debug.print("{s} {d}\n", .{ @tagName(k), @backingInt(k) });}
verified · zig 0.17.0

Prints paper 1 on 0.17. @backingInt is the 0.17 name for @intFromEnum. This source does NOT compile on 0.16: invalid builtin function: '@backingInt' — that is a real compile split, which is why it is tagged since: 0.17.

#041

Tagged Unions

ziglings 056–057

One payload at a time, with the compiler tracking which.

zig
const Shape = union(enum) {    circle: f64,    rect: struct { w: f64, h: f64 },    none,};fn area(s: Shape) f64 {    return switch (s) {        .circle => |r| 3.14159 * r * r,     // capture the payload        .rect => |r| r.w * r.h,        .none => 0,    };}const shape: Shape = .{ .circle = 2.0 };    // init one fieldconst empty = shape == .none;               // tag check: false
  • union(enum) gives every payload a tag; switch must handle all of them (exhaustive).
  • Capture payloads in prongs: .circle => |r| by value, .rect => |*r| for mutation.
  • Field-less members like none carry no data.
  • std.meta.activeTag(s) reads the active tag explicitly; unions are value types.
Run it: complete program
const std = @import("std");const Value = union(enum) { i: i32, s: []const u8 };pub fn main() void {    const v = Value{ .s = "tagged" };    switch (v) {        .i => |n| std.debug.print("int {d}\n", .{n}),        .s => |s| std.debug.print("str {s}\n", .{s}),    }}
verified · zig 0.17.0
#042

Untagged & extern Unions

ziglings 055

Raw field aliasing — you own the active-field bookkeeping.

zig
const Value = union {    int: i32,    float: f64,      // same storage — fields alias};var v: Value = .{ .int = 42 };v.float = 3.5;       // overwrites the same bytes
No tag, no bookkeeping:Nothing tracks which field is active. Reading a field you did not last write is undefined behaviour — the compiler assumes the active field and may optimize accordingly. Use a tagged union(enum) unless an ABI forces otherwise.

extern union gives C-compatible overlay layout for FFI (think C's union); plain union is the in-Zig variant. Both expect you to remember the active field.

#043

Packed Unions

Field aliasing at the bit level over a backing integer.

zig
const Reg = packed union(u2) {    raw: u2,    parts: packed struct(u2) { low: bool, high: bool },};const r: Reg = .{ .raw = 0b10 };// 0.16+: packed unions can be compared for equality:const matches = r == .{ .parts = .{ .low = false, .high = true } };
  • packed union(uN) overlays its fields bit-exactly on a backing integer — the classic register-view tool.
  • 0.16: packed unions support == comparisons and can appear as switch prong items.
#044

Choosing: enum vs union vs struct

A ten-second decision table.

If you need...Reach forData
One of N statesenumnone — just the tag
One of N states, each with dataunion(enum)exactly one active payload
Overlapping views of the same bitsunion / packed union / extern unionyou track the active field
All fields at oncestructeverything, always

A tagged union is Zig's safe version of C's tagged-struct idiom and C++'s std::variant: the tag is compiler-managed, and switch refuses to compile until every case is handled.

Section 8 of 21: Optionals

4 entries

Null without the billion-dollar mistake — ?T is a value or null, and every unwrap is compiler-checked.

#045

Optional Basics

ziglings 045–046, 050

?T is a value or null — test it, default it, or capture it; there is no truthiness.

?T holds a value of T or null. Test with o == null, default with orelse, unwrap-assert with .?, or capture the payload with if (o) |v|.

Create, test, unwrap
const maybe: ?i32 = null;const n: ?i32 = 42;if (n) |v| {    std.debug.print("got {d}\n", .{v});  // payload capture} else {    std.debug.print("nothing\n", .{});}const a = maybe orelse 0;        // 0 — fallback when nullconst b = n.?;                   // 42 — panics if nullstd.debug.print("{d} {d}\n", .{ a, b });
OperationValue presentnull
o orelse dyields oyields d
o.?yields opanic: attempt to use null value
if (o) |v| a else ba, with v boundb
while (o) |v| { ... }body per valueloop ends
Run it: complete program
const std = @import("std");pub fn main() void {    const maybe: ?u8 = 42;    const nothing: ?u8 = null;    // {?d} prints null as "null"; orelse supplies a fallback.    std.debug.print("{?d} {d}\n", .{ maybe, nothing orelse 0 });}
verified · zig 0.17.0
#046

While-Unwrap & Iterators

ziglings 045–046, 050

while (iter.next()) |item| is the idiomatic iterator loop; else fires when the loop ends without break.

An iterator is any type with fn next() ?T — each call yields the next value or null. The while-unwrap loop consumes it: the body runs per value, the loop ends when null arrives.

Custom iterator over ?u32
const Counter = struct {    remaining: u32 = 3,    fn next(self: *Counter) ?u32 {        if (self.remaining == 0) return null;        self.remaining -= 1;        return self.remaining;        // yields 2, 1, 0    }};var it = Counter{};while (it.next()) |item| {            // ?u32 unwrapped per pass    std.debug.print("{d} ", .{item});} else {    std.debug.print("ended, no break\n", .{}); // runs: no break used}

The else clause — on while and for alike — runs only when the loop ended without break; for error unions it takes the last error: else |e|. for (slice, 0..) |item, i| walks items with their index, and multi-sequence for (as, bs) |a, b| zips sequences pairwise.

#047

Optional Pointers

ziglings 045–046, 050

?*T costs nothing extra — null hides in the pointer's spare bit pattern; ?u32 pays for a tag.

?*T occupies exactly the same bytes as *T: address 0 is never a valid pointer, so it encodes null for free. Payloads without a spare bit pattern (?u32, ?bool) need a hidden tag byte. This is why linked-list next fields, tree children, and find-style APIs returning ?usize all use optional pointers.

zig
const Entry = struct {    id: u32,    next: ?*Entry = null,       // linked list: null is free};const Config = struct {    home: ?[]const u8 = null,   // optional slice field    fallback: ?*const Config = null,};fn findIndex(hay: []const u8, needle: u8) ?usize {    for (hay, 0..) |c, i| {        if (c == needle) return i;   // find-style API    }    return null;}
TypeSizeWhy
?*T== @sizeOf(*T)0 is reserved — null is free
?*const T== @sizeOf(*const T)same trick
?u32> @sizeOf(u32)extra tag, padded to alignment
?bool> @sizeOf(bool)no spare bit pattern
#048

Patterns & Gotchas

ziglings 045–046, 050

orelse chains, nested optionals, and why catch is not orelse.

zig
// orelse chain: first non-null winsconst home = env_home orelse env_user orelse "/tmp";// capture payload BY POINTER: mutate in place, no copyif (map.getPtr(key)) |ptr| ptr.count += 1;// nested optional ??T: legal but rare — unwrap twiceconst deep: ??u32 = n;if (deep) |inner_opt| {    if (inner_opt) |v| std.debug.print("{d}\n", .{v});}
  • null has its own singleton type — @TypeOf(null); optionals are not booleans
  • a orelse b orelse c short-circuits to the first non-null
  • nested ??T is allowed but almost always a design smell — prefer ?T or an error union
  • catch belongs to error unions, orelse to optionals — the two do not interchange
x.? panics with attempt to use null value — and that safety check only exists in Debug and ReleaseSafe. In ReleaseFast it is compiled out: undefined behavior. Prefer orelse or if-capture unless the invariant is locally provable.

Section 9 of 21: Error Handling

6 entries

Errors are ordinary values: E!T return types, try/catch, errdefer — no exceptions, no unwinding.

#049

Error Sets

ziglings 021–025, 033

error{...} defines a set of error values — checked at compile time, returned, never thrown.

An error set — error{FileNotFound, OutOfMemory} — is a distinct set of error values, not a class hierarchy. Values coerce upward into any superset for free; anyerror accepts every error that exists.

zig
const OpenError = error{ FileNotFound, AccessDenied };// combine sets: merged superset, coercion is automaticconst IoError = OpenError || error{ EndOfStream };// anyerror: the global set — erases the concrete setvar last: anyerror = error.OutOfMemory;fn open() OpenError!void {    return error.FileNotFound;   // must be in the return set}
FormMeaning
error{A, B}set literal; values are error.A, error.B
E1 || E2merged superset (coercion target)
anyerrorthe global set of all errors
E!Terror union: an E value or a T payload

Error sets are not exceptions. They are return values: an error must be handled at the call site or propagated explicitly, and nothing ever unwinds.

#050

Error Unions & Inferred Sets

ziglings 021–025, 033

E!T is error or value; !T lets the compiler infer the set; try/catch unwrap it.

E!T is a union: an error value or a payload. !T (no set named) means inferred — the compiler collects every error the body can return, and inferred sets compose across call chains. Bind one explicitly as IoError!u32 when you want a stable contract.

zig
fn parse(s: []const u8) !u32 {            // ! = inferred error set    if (s.len == 0) return error.Empty;   // raise: return an error    return try std.fmt.parseInt(u32, s, 10);}const v = parse("42") catch 0;            // fallback valueconst w = parse("42") catch unreachable;  // asserts no errorconst x = parse("nope") catch |e| blk: {  // labeled catch    std.debug.print("failed: {s}\n", .{@errorName(e)});    break :blk 0;};
try
const v = try parse(s);
catch |e| return e
const v = parse(s) catch |e| return e;

try f() is exactly this sugar: unwrap, or return the error from the enclosing function.

FormOn errorOn success
try f();returns the error from this fnyields the value
f() catch 0;yields 0yields the value
f() catch unreachable;panicsyields the value
f() catch |e| handler;runs handler, e in scopeyields the value
Run it: complete program
const std = @import("std");const FlipError = error{Nope};fn flip(coin: bool) FlipError!u8 {    if (!coin) return FlipError.Nope;    return 7;}pub fn main() void {    // catch turns the error into a value; no try, no crash.    std.debug.print("{d} {d}\n", .{ flip(true) catch 0, flip(false) catch 0 });}
verified · zig 0.17.0
#051

Handling Payloads

ziglings 021–025, 033

Unwrap error unions with if/while payload capture; switch on the error value itself.

zig
const r: ReadError!u32 = read();if (r) |v| {                          // success: v is the payload    std.debug.print("ok {d}\n", .{v});} else |e| {                          // error: e is the error value    switch (e) {                      // switch on the error set        error.FileNotFound => create(),        else => return e,             // propagate the rest    }}while (tryConnect()) |conn| {         // body runs on each success    serve(conn);} else |e| return e;                  // runs on the final error

There is no switch on an error union — unwrap with if (r) |v| ... else |e| ... first, then switch the bare error value. A switch (e) over a set must be exhaustive or end in else.

  • @errorName(e) returns the name as []const u8 — the builtin is @errorName, there is no std.error module
  • if (r) |v| { ... } else |e| { ... } — success and error branches in one statement
  • while (attempt()) |v| { ... } else |e| { ... } — retry loops for free
#052

errdefer

ziglings 021–025, 033

errdefer runs cleanup only when an error return passes through its scope.

errdefer arms when execution passes it and fires only when an error return leaves the scope — never on success. Arming it before the resource's own try is pointless: that try already bailed out of the function.

Resource cleanup ordering (LIFO)
const conn = try connect(gpa);   // acquireerrdefer conn.close();           // undo ONLY if we return an errorconst buf = try gpa.alloc(u8, 64);errdefer gpa.free(buf);          // LIFO: freed before conn closeserrdefer std.log.warn("setup failed", .{});   // 0.17: no |e| capturetry conn.handshake();            // any failure here or below:return conn.read();              // log, free buf, close conn, propagate

0.17: errdefer |e| ... is gone — an errdefer takes a plain block or expression, so it cannot name the error it is cleaning up after. Add the context where you catch.

Error capture in errdefer — 0.16 only
const conn = try connect(gpa);errdefer |e| std.log.err("setup failed: {s}", .{@errorName(e)});errdefer conn.close();return conn.handshake();

0.16 let an errdefer capture the error passing through it with |e|. 0.17 removed the capture: the second line is a parse error on 0.17.

The 0.17 migration: split the function
fn setup(gpa: std.mem.Allocator) !Conn {    const conn = try connect(gpa);    errdefer conn.close();            // cleanup stays where the resource is    try conn.handshake();    return conn;}fn start(gpa: std.mem.Allocator) !Conn {    return setup(gpa) catch |e| {    // the error IS in scope here        std.log.err("setup failed: {s}", .{@errorName(e)});        return e;    };}

The split is the pattern: the function that acquires the resource owns the errdefer; the function that catches owns the message. Nothing is lost — the message moves one scope up.

FormFires
defer f();every scope exit
errdefer f();scope exit via error return only
errdefer |e| f(e);removed in 0.17 — plain errdefer { ... } only
success return after armingnothing — the errdefer is skipped
#053

Panics & Unreachable

ziglings 021–025, 033

@panic aborts with no unwinding; unreachable is a contract the optimizer relies on.

zig
std.debug.assert(x > 0);           // "assertion failed" in safe modesif (buf.len > max_len) @panic("buffer overrun by design");fn step(s: Phase) void {    switch (s) {        .start, .running => advance(s),        .done => unreachable,       // invariant: never called when done    }}
  • @panic("msg") prints message + trace and aborts — no unwinding: defers do not run
  • unreachable — reached unreachable code panic in Debug/ReleaseSafe; undefined behavior in ReleaseFast
  • std.debug.assert(cond) — panics in Debug/ReleaseSafe, compiled out in ReleaseFast/ReleaseSmall
  • error return traces print in safe builds — every try the error crossed, like a reverse stack trace
  • gate debug-only code with builtin.mode == .Debug (const builtin = @import("builtin");)
No exceptions, no catch-alls. An error is handled where it occurs or returned explicitly — and error unions cannot cross extern/export boundaries: convert to C-style return codes at the FFI seam.
#054

Error Style Guide

ziglings 021–025, 033

Errors carry no payload — keep sets small, add context where it exists, try liberally.

Error values carry no payload or message. The idiomatic response: small per-module sets, context added at the call site that has it, and errdefer for cleanup.

  • no payloads, no wrapper types — attach context by logging where you have it, plus errdefer
  • keep error sets small and per-module; error{OutOfMemory} is ubiquitous and coerces everywhere
  • try liberally; handle at the call site that actually has context to recover
  • don't use optionals for failures — ?T means *absent*, E!T means *went wrong*
  • returning an error from main prints the error trace and exits nonzero
zig
fn load(gpa: Allocator, path: []const u8) !Config {    const file = try openConfig(path);   // low-level error, no context    defer file.close();    return parseConfig(gpa, file) catch |e| {        std.log.err("config {s}: {s}", .{ path, @errorName(e) }); // context here        return e;                        // propagate the original error    };}

Section 10 of 21: Control Flow

6 entries

Conditions must be real bool; if, loops, and switch are expressions — plus labeled blocks for structured jumps.

#055

if / else if / else

ziglings 009–010

Conditions must be genuine bool; if is an expression — that's why there is no ternary.

No truthiness: if (ptr) and if (n) are compile errors — compare explicitly. As an expression, every branch must yield the same type, which is exactly what the ternary would do.

zig
const x: i32 = 7;// statement form: condition must be boolif (x > 5) std.debug.print("big\n", .{});// expression form: replaces the ternaryconst parity: []const u8 = if (x % 2 == 0) "even" else "odd";// payload sugar (see Optionals / Error Handling)if (maybe) |v| use(v);                     // optionalif (result) |v| use(v) else |e| fail(e);   // error union
  • braces are optional for a single statement; zig fmt keeps whatever you wrote
  • when used as an expression, all branches must yield one common type
  • if (o) |v| unwraps an optional; if (r) |v| ... else |e| unwraps an error union
#056

while

ziglings 011–014

while with a continue-expression, labeled break, and an else clause — no do-while.

while (cond) { } repeats until the condition is false. The continue-expression : (i += 1) runs after every pass — including after continue — making it the safest place for increments.

zig
var i: u32 = 0;while (i < 5) : (i += 1) {    // continue-expr runs after each pass    if (i == 3) continue;    if (i == 4) break;}// no do-while: use while (true) + breakwhile (true) {    if (ready()) break;}// else: runs when the condition ends the loop WITHOUT a breakwhile (poll()) |v| {          // optional / error-union unwrap    if (v == 0) break;} else flush();               // poll() ran dry
  • break/continue can target a label: break :outer, continue :outer
  • else after while: fires when the loop ended without break (also else |e| for error unions)
  • no do-while — write while (true) plus a break
#057

for & Ranges

ziglings 015–016, 095, 100–101

for walks exclusive ranges and slices, zipping sequences with an optional index.

for (0..n) |i| iterates the exclusive range 0..n. Sequences zip by position — for (xs, ys, 0..) |x, y, i| — and all lengths must match (runtime check in safe builds).

zig
for (0..3) |i| {                      // exclusive range: 0, 1, 2    std.debug.print("{d} ", .{i});}const xs = [_]u8{ 10, 20, 30 };const ys = [_]u8{ 1, 2, 3 };for (xs, ys, 0..) |x, y, i| {         // zip: item, item, index    std.debug.print("{d}+{d}@{d} ", .{ x, y, i });}                                     // equal lengths, runtime-checkedfor (xs) |x| {    if (x == 20) continue;    if (x == 30) break;} else std.debug.print("no break\n", .{});
  • _ discards a slot: for (xs, 0..) |_, i| iterates indices only
  • no reverse ranges — index backwards by hand, or std.mem.reverse a copy first
  • mutate in place with for (slice) |*item| item.* += 1
  • else on for runs when the loop finished without break
#058

switch

ziglings 030–031, 108

Exhaustive by default; ranges with ...; prongs capture tagged-union payloads.

switch is exhaustive by default: cover every value or add else. It works as expression or statement, and captures |v| bind payloads — especially for tagged unions.

zig
const label = switch (n) {          // expression: prongs yield a value    0 => "zero",    1, 2, 3 => "small",             // value list    4...8 => "medium",              // inclusive range    else => "large",};fn area(s: Shape) f32 {             // union(enum): capture payloads    return switch (s) {        .circle => |r| r * r * 3.14159,        .rect => |d| d[0] * d[1],    };                              // exhaustive: no else needed}
ProngMatches
1 => ...a single value
1, 2 => ...a list of values
1...5 => ...an inclusive range
.circle => |r| ...payload capture on union(enum)
else => ...everything unmatched
  • prongs are comma-separated — trailing comma when they span lines
  • switch works on ints, bools, enums, error sets, and union(enum)s — not strings or floats (use if/else + std.mem.eql)
  • 0.16: prongs accept packed struct/union items (.{ .b = 3 }) and decl literals as values
#059

Labeled Blocks & Loops

ziglings 062–063

Labels turn nested loops and blocks into structured goto — and blocks can yield values.

A label names a loop or block so break :label / continue :label can target it from any nesting depth. Labeled blocks double as multi-step expressions.

zig
outer: for (rows) |row| {    for (row) |cell| {        if (cell < 0) break :outer;     // exits BOTH loops        if (cell == 0) continue :outer; // next outer iteration    }}const idx = blk: {                      // labeled block yields a value    for (names, 0..) |name, i| {        if (std.mem.eql(u8, name, want)) break :blk i;    }    break :blk null;                    // not found};
  • labels work on blocks, for, and while alike
  • continue :label restarts the labeled loop's next iteration
  • break :blk value makes a block an expression — replaces goto and early-multi-break acrobatics
Run it: complete program
const std = @import("std");pub fn main() void {    outer: for (0..5) |i| {        for (0..5) |j| {            if (i * j == 6) {                std.debug.print("{d} * {d}\n", .{ i, j });                break :outer; // leaves BOTH loops, not just the inner one            }        }    }}
verified · zig 0.17.0
#060

unreachable

ziglings 032

Proves impossibility to the compiler — or costs you UB in optimized builds.

unreachable asserts a line can never execute. The compiler may optimize based on that promise. Safe modes verify it at runtime: panic reached unreachable code. ReleaseFast believes you: undefined behavior.

zig
fn drive(s: State) void {    switch (s) {        .parked, .driving => move(s),        .scrapped => unreachable,   // invariant: can't happen here    }}
Never validate input with unreachable — hostile data hitting it in ReleaseFast is memory corruption, not a crash. Use @panic, try, or else => return error.X for anything reachable.

Section 11 of 21: Functions

6 entries

Required return types, immutable params, no closures — functions are plain, predictable declarations.

#061

Declaring Functions

ziglings 018–020

Return type required, params immutable, no defaults — and pub controls visibility.

The return type is REQUIRED — use void when there is nothing to return. Parameters are immutable bindings, and there are no default or named arguments.

zig
/// Adds two integers.pub fn add(a: i32, b: i32) i32 {    return a + b;}pub fn logHello(name: []const u8) void {  // void: no return value    std.debug.print("hello {s}\n", .{name});    // params are const: assigning to name is a compile error}
  • pub exposes a decl to @importers of this file — private otherwise
  • parameters are const; to change one, copy into a local first
  • /// doc comments attach to decls and appear in autodoc
  • no overloading — use distinct names or comptime dispatch
#062

Multiple Return Values

ziglings 018–020

No multi-return sugar — return a struct/tuple, an optional, an error union, or use out-params.

Zig has no multi-value return sugar — pick a shape: !T for failure, ?T for absence, a struct or anonymous tuple for several values, *T out-params for mutation.

zig
fn divMod(a: u32, b: u32) struct { q: u32, r: u32 } {    return .{ .q = a / b, .r = a % b };}fn demo() void {    const q, const r = divMod(17, 5);   // 3 and 2 — positional (0.14+)    std.debug.print("{d} {d}\n", .{ q, r });}// alternatives: ?T (absent), E!T (failure), *T (out-param)fn indexOf(s: []const u8, c: u8) ?usize {    for (s, 0..) |ch, i| if (ch == c) return i;    return null;}_ = .{ demo, indexOf };
  • tuple return type: struct { u32, u32 } — anonymous, destructured by position
  • destructuring since 0.14: const .{ .q = q, .r = r } = ...;
  • _ discards a destructured slot you don't need
#063

Passing Arguments

ziglings 018–020

Pass-by-value with compiler-optimized lowering — pointers only for mutation or sharing.

Arguments pass by value; the compiler picks the cheap lowering, so don't contort signatures over sizes. Reach for pointers when you must mutate the caller's data or share it — and remember params are immutable, so *T is the only way to write back.

zig
fn byValue(p: Point) Point {         // copy — fine for small data    return .{ .x = p.x * 2, .y = p.y * 2 };}fn scale(p: *Point, f: f32) void {   // mutate the caller's value    p.x *= f;    p.y *= f;}fn total(items: []const u32) u32 {   // read-only view, any length    var sum: u32 = 0;    for (items) |v| sum += v;    return sum;}
SituationSignature
read-only, small datapass T by value
read-only, big data[]const T or *const T
mutate caller's data*T
accept an arrayparam []const T — [N]T coerces
optional argument?T explicitly (no default args)
#064

export, extern & callconv

ziglings 018–020

export publishes C-visible symbols, extern declares them, callconv pins the ABI.

The calling convention decides the ABI. export/extern bridge Zig to C and the linker; inlining is a call-site hint: @call(.always_inline, f, .{args}).

zig
export fn zig_callback(x: i32) i32 {   // C-visible symbol    return x * 2;}extern "c" fn printf(fmt: [*:0]const u8, ...) c_int; // C variadicfn cStyle(x: u32) callconv(.c) u32 {   // explicit C ABI (0.14+)    return x + 1;}fn square(x: i32) i32 {                       // plain fn: Zig has no inline-fn keyword    return x * x;}const y = @call(.always_inline, square, .{ 4 });  // force inlining AT the call_ = .{ y, zig_callback, cStyle, printf };
  • export fn f() emits the symbol for C/linkers; extern declares one defined elsewhere
  • extern "c" names the library; variadic ... requires the C calling convention
  • callconv(.c) on a normal fn pins the C ABI (lowercase since 0.14)
  • callconv(.naked) for asm-only stubs — no prologue or epilogue
  • inline fn forces inlining at each call site
#065

Function Pointers

ziglings 018–020

*const fn (...) T types, &f spelling, no closures — context goes through a parameter.

A function pointer's type is *const fn (i32, i32) i32. Take a function's address with &f — the safest spelling — then call it like a function. There are no closures: pass captured state through an explicit context parameter.

zig
fn add(a: i32, b: i32) i32 { return a + b; }fn sub(a: i32, b: i32) i32 { return a - b; }const Op = *const fn (i32, i32) i32;fn apply(op: Op, a: i32, b: i32) i32 {    return op(a, b);}const f: Op = &add;                    // &fn is the canonical spellingstd.debug.print("{d} {d}\n", .{ apply(f, 3, 4), apply(&sub, 3, 4) });
  • used for callbacks, interrupt vectors, and hand-rolled vtables (see comptime & Generics for the zero-cost alternative)
  • capture state C-style: fn cb(ctx: *anyopaque, x: u32) void with the context as the first parameter
  • comptime fn parameters specialize per function: fn wrap(comptime f: fn () void)
#066

Recursion

ziglings 018–020

Runtime recursion just works (until the stack); comptime recursion needs an eval-branch budget.

Runtime recursion is plain stack recursion — nothing special, nothing detected. Comptime recursion is bounded by the eval branch quota, raised with @setEvalBranchQuota.

zig
fn fib(n: u32) u64 {                  // runtime: plain stack recursion    return if (n < 2) n else fib(n - 1) + fib(n - 2);}fn Fib(comptime n: u32) u64 {         // comptime: quota-bounded    return if (n < 2) n else Fib(n - 1) + Fib(n - 2);}comptime {    @setEvalBranchQuota(1_000_000);   // default quota is only 1000    _ = Fib(25);                      // evaluated during compilation}
  • infinite runtime recursion dies with a stack overflow — not detected, no tail-call guarantee
  • recursive generic instantiation can explode compile times — memoize or flatten
  • @setEvalBranchQuota raises the comptime step budget for the current evaluation

Section 12 of 21: defer & Cleanup

4 entries

Scope-exit cleanup: defer, errdefer, and the acquire/release discipline that replaces RAII.

#067

defer

ziglings 027–029

Runs at the END OF SCOPE — the block, not the function — always, in LIFO order.

defer schedules a statement for the end of its enclosing block — not the function. Sibling defers run LIFO (last registered, first run) on every exit path: return, error return, break.

Mutex + heap example
fn demo(gpa: Allocator) !void {    const data = try gpa.alloc(u8, 128);    defer gpa.free(data);           // paired right at acquisition    lock.lock();    defer lock.unlock();            // LIFO: runs BEFORE free    // ... work — early returns, errors, breaks: all safe}
Defers do not run on panic or abort — the process dies on the spot. One more reason panics are for bugs and errors are for expectations.
Run it: complete program
const std = @import("std");pub fn main() void {    std.debug.print("a\n", .{});    defer std.debug.print("c\n", .{});    defer std.debug.print("b\n", .{}); // defers run last-in, first-out}
verified · zig 0.17.0
#068

errdefer

ziglings 027–029

Same LIFO machinery, but only on the failure path — combine for commit/rollback.

errdefer fires only when an error return passes through its scope — never on success. The classic combo: errdefer rollback right after acquiring, commit as the last step. Two lines make a transaction.

zig
const conn = try connect(gpa);errdefer conn.close();          // only on error returntry conn.handshake();           // bail? -> closed for youtry tx.begin();errdefer tx.rollback();         // failure pathtry tx.write(records);tx.commit();                    // success path — keep it last
Exit pathdefererrdefer
success returnrunsskipped
error return / failed tryrunsruns
leave the scope via breakrunsskipped
panic / abortskippedskipped
#069

Scope Rules & Gotchas

ziglings 027–029

defer is block-scoped: in a loop body it fires every iteration — or holds resources the whole loop.

defer binds to the nearest enclosing block. In a loop body that is one iteration; inside an if block, that block; at function top, the function.

zig
fn scan(gpa: Allocator, paths: []const []const u8) !void {    for (paths) |path| {        const f = try open(path);            // acquire per iteration        defer f.close();                     // released per iteration        const buf = try gpa.alloc(u8, 1024); // also per iteration        defer gpa.free(buf);                 // LIFO in this body:        try process(f, buf);                 // free buf, then close f    }}
  • defer reads variables at RUN time, not at registration — defer log(i) sees i as it is when the scope exits
  • want the value as it was at defer-time? snapshot first: const j = i; defer use(j);
  • leaving the scope via break still runs defers — only panic/abort skips them
A defer outside a loop body holds the resource for the whole loop. If each iteration should own the resource, move the acquire/defer pair into the body.
#070

Common Cleanup Table

ziglings 027–029

acquire → defer release, immediately, before any try in between.

The discipline that makes defer work: every acquire is IMMEDIATELY followed by its release deferral — before any try, return, or second acquire can slip between them.

AcquireReleaseNotes
gpa.alloc(u8, n)gpa.free(mem)same allocator, same scope
open a filef.close()whatever opened it closes it
lock.lock()lock.unlock()std.Thread.Mutex
acquire a refcountrelease itbalance every +1 with a -1
tx.begin()tx.commit()errdefer tx.rollback()
suspendresumekeep the pair visually adjacent
zig
const mem = try gpa.alloc(u8, size);defer gpa.free(mem);             // <- no try between these two linesconst out = try dest.begin();    // next resourcedefer out.finish();              // paired before any risk

Section 13 of 21: comptime & Generics

7 entries

Run arbitrary code at compile time — generics are just functions on type, with no macro preprocessor in sight.

#071

comptime Fundamentals

ziglings 064–068

comptime marks code the compiler executes at build time — params, vars, and blocks.

comptime marks code the compiler runs at build time: parameters, variables, whole blocks. All generics, type values, and default values are comptime — this one mechanism replaces C macros, templates, and pre-build codegen.

zig
fn repeat(comptime n: u32, msg: []const u8) void {    comptime var i: u32 = 0;              // comptime variable    inline while (i < n) : (i += 1) {     // unrolled at compile time        std.debug.print("{s} ", .{msg});    }}const big = 1_000_000_000_000;   // comptime_int: unbounded, exactconst small: u8 = 200;           // coerced to u8 at compile time
  • comptime_int / comptime_float: unbounded, exact literal types — they coerce into concrete types on use
  • if (comptime cond) evaluates now and prunes the untaken branch from the binary
  • a comptime parameter creates a distinct instantiation per value
#072

Generic Functions

ziglings 069–072

type is a comptime value — take it as a parameter and the fn gets monomorphized per call.

A type parameter makes the function generic — T is just a comptime value. Every distinct T produces a fresh monomorphized copy of the body; there is no runtime polymorphism involved.

zig
fn max(comptime T: type, a: T, b: T) T {    return if (a > b) a else b;}const m1 = max(i32, 3, 9);        // explicit type argumentconst m2 = max(u8, 1, 2);         // each T = a fresh instantiationfn sum(items: anytype) i64 {     // anytype: inferred param type    var total: i64 = 0;    for (items) |x| total += x;    return total;}
  • anytype: infer the parameter type from the call site
  • @hasDecl(T, "name") / @hasField(T, "name") — duck-type checks on capabilities
  • constraints are implicit — misuse fails where used; add @compileError for clear messages
#073

Generic Types (type-returning fns)

ziglings 073–075

A function returning type is a generic type; @This() names the struct from inside.

Generic types are functions that return type. The struct declared inside is a fresh type for every T; identical arguments always yield the identical type.

Canonical generic container
fn List(comptime T: type) type {    return struct {        items: []T,        len: usize = 0,        const Self = @This();    // name this struct from inside        fn push(self: *Self, item: T) void {            self.items[self.len] = item;            self.len += 1;        }    };}const IntList = List(i32);       // fresh type, monomorphized
  • @This() — the innermost type's own name, for Self-style aliases and methods
  • methods close over the generic parameter — no extra plumbing
  • instantiate like any decl: const IntList = List(i32);
#074

inline for / inline while

ziglings 066–068

Unroll loops at comptime — one stamped-out copy per iteration.

inline for / inline while force unrolling: the body is stamped out once per iteration at compile time. Required whenever each iteration must generate distinct code from comptime values.

Unrolled field walk — 0.16 spelling
const Point = struct { x: u32 = 0, y: u32 = 0 };fn zeroAll(point: *Point) void {    inline for (@typeInfo(Point).@"struct".fields) |field| {        @field(point, field.name) = 0;    // x, then y — unrolled    }}var origin = Point{ .x = 3, .y = 4 };zeroAll(&origin);   // the call is what makes the compiler analyze the loop

0.17 removed @typeInfo(T).@"struct".fields — the compiler says no field named "fields" in struct lang.Type.Struct. The 0.17 form is the next block. The trailing call matters: Zig analyzes a function body only when the function is called, so an un-called helper hides its own errors from every gate.

Unrolled field walk — 0.17 spelling
const Point = struct { x: u32 = 0, y: u32 = 0 };fn zeroAll(point: *Point) void {    inline for (@typeInfo(Point).@"struct".field_names) |name| {        @field(point, name) = 0;    // x, then y — unrolled    }}var origin = Point{ .x = 3, .y = 4 };zeroAll(&origin);   // the call is what makes the compiler analyze the loop

0.17 iterates field_names — the name is the loop value, not a .name field. Pair it with field_types when the body needs the type. 0.16 rejects this spelling: no field named 'field_names' in struct builtin.Type.Struct.

  • field.name is a comptime string, and @field(obj, name) needs a comptime-known name — a runtime loop can't supply either
  • 0.17: the loop source is @typeInfo(T).@"struct".field_names — the name IS the loop value; field_types is the parallel slice of types
  • plain loops stay runtime loops when nothing per-iteration is comptime — inline loops bloat binaries
  • inline while unrolls the same way
Run it: complete program
const std = @import("std");inline fn add(comptime T: type, a: T, b: T) T {    return a + b; // specialized per call site, no generic runtime cost}pub fn main() void {    std.debug.print("{d} {d}\n", .{ add(i8, 1, 2), add(f32, 1.5, 2.5) });}
verified · zig 0.17.0
#075

Type-Creating Builtins (0.16)

since 0.16ziglings 064–065

@Type is gone in 0.16 — construct types with focused builtins instead.

@Type was removed in 0.16 — constructing types now goes through focused builtins, one per kind. Reach for them only when the type cannot be spelled directly.

BuiltinBuildsSketch
@Intinteger type@Int(signedness, bits)
@Floatfloat type@Float(bits)
@Pointerpointer typesize / child / alignment args
@Arrayarray type@Array(len, child)
@VectorSIMD vector@Vector(len, child)
@Tupletuple type@Tuple(&.{ u8, u16 })
@Structstruct typefields arg — see docs
@Unionunion typesee docs
@Enumenum typesee docs
@Opaqueopaque typesee docs
@Optionaloptional type@Optional(u32) → ?u32
@ErrorUnionerror unionset + payload args
@ErrorSeterror setnames arg — see docs
@Fnfunction typesee docs
@EnumLiteralenum literal typethe type of .tag
These shipped with @Type's removal in 0.16 and signatures are still settling — check the std docs for your exact version. For most code, spelling types directly (?u32, [4]u8, *T) beats constructing them.
#076

Metaprogramming Toolkit

ziglings 064–065, 069–075

Reflect, generate, and fail fast — the everyday comptime toolbox.

Reflection and generation in one toolbox — everything here is evaluated during the build, never at runtime.

ToolWhat it does
@typeInfo(T)reflect — tags like .int, .@"struct", .pointer, .error_union
@field(obj, "name")access a field or decl by comptime name
@hasField(T, "name")does the struct have this field?
@typeName(T)human-readable type name
@sizeOf(T) / @offsetOf(T, "f")layout facts
@call(.auto, f, .{args})call with a comptime-built argument tuple
@compileError("msg")fail compilation with your message
@compileLog(...)print values during compilation — remove before shipping
@setEvalBranchQuota(n)raise the comptime step budget (default 1000)
@embedFile(path)file contents as *const [n:0]u8 at comptime
std.meta.fields(T)0.16: field list as a comptime slice. 0.17: a compileError — deprecated in favor of @typeInfo; use @typeInfo(T).@"struct" with field_names + field_types, or std.meta.fieldNames(T) in a plain for (inline for breaks on 0.17)
usingnamespaceremoved since 0.15 — no replacement; declare and import explicitly
Comptime type validation — 0.16 spelling
fn checkPairs(comptime T: type) void {    inline for (@typeInfo(T).@"struct".fields) |f| {        if (@sizeOf(f.type) == 0) {            @compileError("zero-sized field: " ++ f.name);        }    }}const Good = struct { ok: u32, name: []const u8 };comptime { checkPairs(Good); }   // passes: every field has a sizeconst Bad = struct { ok: u32, ghost: u0 };// comptime { checkPairs(Bad); }  // compile error: zero-sized field: ghost

The failing call is commented out: it is the example, not a bug — uncommenting the last line makes the build fail with your own message. A comptime call at container scope needs the block form, comptime { checkPairs(T); }.

Comptime type validation — 0.17 spelling
fn checkPairs(comptime T: type) void {    const s = @typeInfo(T).@"struct";    inline for (s.field_names, s.field_types) |name, field_type| {        if (@sizeOf(field_type) == 0) {            @compileError("zero-sized field: " ++ name);        }    }}const Good = struct { ok: u32, name: []const u8 };comptime { checkPairs(Good); }   // passes: every field has a sizeconst Bad = struct { ok: u32, ghost: u0 };// comptime { checkPairs(Bad); }  // compile error: zero-sized field: ghost

0.17 has no field list: @typeInfo(T).@"struct".fields answers no field named "fields" in struct lang.Type.Struct, so the walk pairs the parallel slices field_names and field_types. 0.16 rejects this spelling with no field named 'field_names' in struct builtin.Type.Struct.

#077

Duck-Typed Interfaces (no vtables)

Interfaces are comptime checks — or explicit fn-pointer structs when the type is runtime-chosen.

Compile-time interface check (ziglings 084 pattern)
fn describe(comptime T: type, thing: T) void {    comptime {        if (!@hasDecl(T, "describe"))            @compileError(@typeName(T) ++ " needs a describe() decl");    }    thing.describe();          // duck typing, resolved at compile time}const Cat = struct {    fn describe(_: Cat) void {          // unused param: name it _        std.debug.print("meow\n", .{});    }};

When the concrete type is chosen at runtime, comptime duck typing is out. Build a vtable by hand — a struct of function pointers plus a context pointer. That is exactly how std.Io.Writer / std.Io.Reader dispatch since 0.15.

Hand-rolled vtable
const Speaker = struct {    ctx: *anyopaque,    speakFn: *const fn (*anyopaque) void,    fn speak(self: Speaker) void {        self.speakFn(self.ctx);      // runtime dispatch    }};
  • comptime interfaces: zero cost, monomorphized — but the type must be known at compile time
  • vtable interfaces: one copy of code, runtime dispatch — works with runtime-chosen types
  • *anyopaque context + @ptrCast back is the standard state-capture idiom (there are no closures)

Section 14 of 21: Memory & Allocators

5 entries

Explicit allocation: no GC, no hidden malloc.

#078

The Allocator Interface

ziglings 096

Every allocation goes through a passed-in std.mem.Allocator — nothing allocates behind your back.

Zig has no hidden allocations. Anything that needs memory takes a std.mem.Allocator — by convention it is the first parameter. The allocator is a small vtable interface (ptr + vtable), so the caller picks the strategy (arena, fixed buffer, C, page, ...).

allocatereleasereturns
create(T)destroy(ptr)!*T
alloc(T, n)free(slice)![]T
allocSentinel(T, n, 0)free(slice)![:n]T
dupe(T, slice)free![]T
realloc(slice, n)free![]T
remap(slice, n)free?[]T — may move
resize(slice, n)—bool — in-place only

Sentinel copy: dupeZ(T, slice) → ![:0]T. 0.17 removed it — the next block is the 0.17 spelling. dupeSentinel(T, slice, 0) works on 0.16 as well.

Sentinel copy: dupeSentinel(T, slice, 0) → ![:0]T. 0.17 deleted dupeZ outright: no field or member function named 'dupeZ' in 'mem.Allocator' — a compile break, not a style preference. dupeSentinel also compiles on 0.16.

All allocating operations return errors (!) — out of memory is an ordinary error value, never a panic. The caller owns the result and must free it (or hand the job to an arena).

Allocator as first parameter
fn readName(gpa: std.mem.Allocator) ![]u8 {
    const buf = try gpa.alloc(u8, 32);
    defer gpa.free(buf);
    buf[0] = 'z';
    return try gpa.dupe(u8, buf[0..1]); // caller frees this copy
}
#079

ArenaAllocator

Allocate freely, free everything at once — the workhorse for parsers, CLIs and request handling.

An arena hands out allocations from big chunks it grabs from a child allocator. Individual free is not needed (or possible for single items) — everything is released at once by deinit().

Scratch memory for one operation (0.17)
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit(); // frees everything allocated below
const a = arena.allocator();

const tmp = try a.alloc(u8, 64);
@memset(tmp, 0); // scratch: no per-slice frees needed
const msg = try a.print("parsed {d} tokens", .{3}); // 0.17: print is on the allocator
// tmp and msg are arena memory - released by the defer above
const out = try gpa.dupe(u8, msg); // only the result escapes
_ = out;

0.17 moved formatting onto the allocator as print. 0.16 has no such method: no field or member function named 'print' in 'mem.Allocator' — a compile break, so the 0.16 view shows std.fmt.allocPrint instead.

Scratch memory for one operation (0.16)
var arena = std.heap.ArenaAllocator.init(gpa);
defer arena.deinit(); // frees everything allocated below
const a = arena.allocator();

const tmp = try a.alloc(u8, 64);
@memset(tmp, 0); // scratch: no per-slice frees needed
const msg = try std.fmt.allocPrint(a, "parsed {d} tokens", .{3}); // 0.16: formatting lives in std.fmt
// tmp and msg are arena memory - released by the defer above
const out = try gpa.dupe(u8, msg); // only the result escapes
_ = out;

std.fmt.allocPrint compiles on 0.17 too — it is just not the spelling to write there. On 0.16 the allocator method a.print does not exist at all: no field or member function named 'print' in 'mem.Allocator'.

  • .init(child) — wrap any allocator; .allocator() — get the interface; .deinit() — free all
  • reset(.retain_capacity) — keep the memory, drop the allocations: reuse the same arena between phases (per frame, per request, per iteration)
  • Ideal for CLIs, parsers, request handling: one arena per unit of work
  • Since 0.16 the arena is thread-safe and lock-free
Run it: complete program
const std = @import("std");pub fn main(init: std.process.Init) !void {    var arena = std.heap.ArenaAllocator.init(init.gpa);    defer arena.deinit();    const a = arena.allocator();    const first = try a.dupe(u8, "scratch");    std.debug.print("{s}\n", .{first});    // Keep the capacity, drop the allocations: same arena, second phase.    _ = arena.reset(.retain_capacity);    const second = try a.dupe(u8, "reused");    std.debug.print("{s}\n", .{second});}
verified · zig 0.17.0
#080

The Development Allocator

since 0.16

Leak and double-free detection for development builds: std.heap.DebugAllocator in 0.16, std.heap.SafeAllocator in 0.17.

SafeAllocator — the 0.17 development setup
var safe = std.heap.SafeAllocator.init(std.heap.page_allocator, .{}); // options are the SECOND argument
defer _ = safe.deinit();      // deinit returns the LEAK COUNT (usize), not .ok
const a = safe.allocator();   // a SafeAllocator is NOT a mem.Allocator
const buf = try a.alloc(u8, 16);
a.free(buf);                  // free it - SafeAllocator reports leaks on exit

init(backing, options) takes TWO arguments and the options are SafeAllocator.Options (stack_trace_frames, check_write_after_free, canary, bucket_size_log2, block_size_log2). deinit returns the number of leaks, so the 0.16 idiom assert(gpa.deinit() == .ok) does not compile here: incompatible types: 'usize' and '@EnumLiteral()'. 0.16 has no SafeAllocator at all: root source file struct 'heap' has no member named 'SafeAllocator'.

DebugAllocator — the 0.16 development setup
var gpa: std.heap.DebugAllocator(.{}) = .init; // config goes in the TYPE
// .init is a value, not a function: .init(.{}) does not compile
defer std.debug.assert(gpa.deinit() == .ok); // .ok == no leaks
const allocator = gpa.allocator();   // the DebugAllocator is NOT an Allocator

const n = try allocator.create(u32);
n.* = 5;
defer allocator.destroy(n);

This block compiles unchanged on 0.17 — the tab is curation, not a compiler break. Two traps, identical on both compilers: .init is a value, not a function (.init(.{}) → type '...DebugAllocator(...)' not a function), and a DebugAllocator is not an allocator — calling gpa.alloc directly gives 'alloc' is not marked 'pub'. Call .allocator().

0.17 renamed the development allocator again. In std/heap.zig the declaration pub const DebugAllocator carries the comment **Deprecated; use SafeAllocator**, DebugAllocatorConfig carries **Deprecated; use SafeAllocator.Options**, and std.heap.Check — the .ok / .leak enum deinit used to return — is marked **Deprecated. All three still compile** on 0.17: nothing forces the change, which is why the 0.16 block above is a curation tab. The spelling to write on 0.17 is std.heap.SafeAllocator: it wraps a backing allocator and adds canaries, write-after-free checks, double-free panics and stack traces, and its deinit returns the leak count.

In 0.16 std.heap.DebugAllocator is the development allocator. In Debug builds it tracks allocations and reports leaks and double-frees with stack traces; gpa.deinit() returns std.heap.Check.ok when nothing leaked. Config goes in the TYPE parameter: std.heap.DebugAllocator(.{ .stack_trace_frames = 12 }).

GeneralPurposeAllocator was renamed std.heap.DebugAllocator in 0.16 — the old name compiles on neither release: root source file struct 'heap' has no member named 'GeneralPurposeAllocator'. Config always goes in the type parameter, never in an init call.

allocatorreach for it when
std.heap.SafeAllocator.init(backing, .{})development default: leaks, double-frees, write-after-free, canaries
std.heap.DebugAllocator(.{})legacy: compiles on 0.17, marked Deprecated; use SafeAllocator
std.heap.ArenaAllocatormany small allocations, freed all at once
std.heap.c_allocatoryour program links libc anyway
std.heap.page_allocatorraw OS pages, no bookkeeping — a fine backing allocator
std.heap.FixedBufferAllocatorno-heap targets, embedded, bounded scratch
std.heap.smp_allocatorReleaseFast multi-threaded programs
allocatorreach for it when
std.heap.DebugAllocator(.{})default in development: leak / double-free checks
std.heap.smp_allocatorReleaseFast multi-threaded programs (0.16)
std.heap.ArenaAllocatormany small allocations, freed all at once
std.heap.c_allocatoryour program links libc anyway
std.heap.page_allocatorraw OS pages, no bookkeeping, coarse
std.heap.FixedBufferAllocatorno-heap targets, embedded, bounded scratch
#081

Lifetime Rules

No GC: freed memory stays freed. Ownership is a convention you enforce with discipline and tooling.

  • Freed memory stays freed — every alloc needs exactly one free (or an arena deinit)
  • Use-after-free and double-free are UB; the development allocator (DebugAllocator on 0.16, SafeAllocator on 0.17) turns them into clear panics in Debug
  • Slices from an allocator are only valid while the allocator lives — keep it alive as long as the data
  • resize returns bool and only succeeds in place; remap may move — always use the returned slice, old pointers can dangle after a grow/shrink
  • Never free stack memory through an allocator; never return a slice that points into a local buffer
UB in one line:Using a slice after free (or after arena deinit / reset) is undefined behavior. In Debug builds std.heap.DebugAllocator catches it; in ReleaseFast it is silent corruption.
UB in one line:Using a slice after free (or after arena deinit / reset) is undefined behavior. In Debug builds std.heap.SafeAllocator catches it — check_write_after_free is on by default in Debug; in ReleaseFast it is silent corruption.
remap may move your memory
fn grow(gpa: std.mem.Allocator) !void {
    const p = try gpa.alloc(u8, 8);
    const q = gpa.remap(p, 16) orelse return error.OutOfMemory;
    // p may be invalid now - use q from here on
    @memset(q, 0);
    gpa.free(q);
}
#082

Patterns & Pitfalls

Arena per request, allocator as first parameter, and what to do about deinit() results.

  • Arena per request: one arena per unit of work, reset(.retain_capacity) between iterations
  • Pass the allocator down: functions take gpa: std.mem.Allocator as first parameter — no global heap
  • Store an allocator in a struct only if the object owns its allocations; prefer taking it per call (unmanaged containers do exactly this since 0.15)
  • _ = gpa.deinit(); — discard the leak-report result when you intentionally leak at process exit. 0.16 returns Check.ok / Check.leak; 0.17 SafeAllocator.deinit() returns the leak count
  • Test for leaks with std.testing.allocator — it fails the test on any unfreed memory. It is the development allocator wired into the test runner: DebugAllocator on 0.16, SafeAllocator on 0.17 (see Testing)
Arena inside, allocator passed down
const Parser = struct {
    gpa: std.mem.Allocator,

    fn parse(self: *Parser) !void {
        var arena = std.heap.ArenaAllocator.init(self.gpa);
        defer arena.deinit(); // scratch memory freed in one shot
        const tmp = arena.allocator().alloc(u8, 64) catch return error.OutOfMemory;
        _ = tmp;
        // long-lived results allocate from self.gpa instead
    }
};

Section 15 of 21: Standard Library

9 entries

Formatting, containers, hashing, files, processes — and the 0.15/0.16 API shake-up.

#083

Printing & Writers (0.16)

since 0.16ziglings 002, 099

std.debug.print for quick stderr output; stdout goes through the std.Io writer interface.

std.debug.print("...", .{args}) writes formatted text to stderr, cannot fail, and works in every build mode and target. For stdout you go through the std.Io interface.

stderr vs stdout
// stderr, formatted - the everyday printf:
std.debug.print("x={d} name={s}\n", .{ x, name });

// stdout, raw bytes (0.16, from "Juicy main"):
try std.Io.File.stdout().writeStreamingAll(init.io, "hello\n");

// buffered formatted stdout (0.16+): writer() takes the io handle
var buffer: [1024]u8 = undefined;
var w = std.Io.File.stdout().writer(init.io, &buffer);
try w.interface.print("count={d}\n", .{ n });
try w.interface.flush();

The 0.15/0.16 writer signatures are still settling — see the std docs for your exact version.

specifiermeaning
{s}string / bytes
{d}int or float, decimal
{c}character
{x} / {X}hexadecimal, lowercase / uppercase
{b}binary
{o}octal
{e}scientific notation
{?}optional of a formattable value
{any}anything (debug formatting)
{f}call the type's own .format method (since 0.15)
{{ / }}literal braces
{d:0>4}width 4, fill 0, align right
{s:^10}width 10, centered
Quoted output — `{q}` and `{qf}`
const raw: []const u8 = "café \"quo\"\n\t\x01";
const q = try a.print("{q}", .{raw});   // "café \"quo\"\n\t\x01"
const id = try a.print("hello {qf} world", .{std.zig.fmtId("he\"llo")});
// hello "@\"he\\\"llo\"" world

{q} wraps a string in double quotes and escapes \n \r \t \\ " plus ASCII control characters, invalid UTF-8, non-ASCII line endings and BOM as \xNN. Printable non-ASCII passes through — café and 😎 stay readable. {qf} does the same escaping around a type's own format method.

Quoting on 0.16 — `{f}` with `fmtId`
const s = try std.fmt.allocPrint(
    arena.allocator(),
    "hello {f} world",
    .{std.zig.fmtId("he\"llo")},
);
// hello @"he\"llo" world

0.16 has **no {q} and no {qf}** — {q} answers cannot format slice without a specifier. std.zig.fmtId + {f} is the 0.16 route, and it prints the Zig identifier form (@"...") rather than a plain quoted string.

specifiermeaning0.16
{q}double-quote-escaped stringcannot format slice without a specifier
{qf}type's format method, double-quote escapedinvalid format string 'qf'
  • Arguments are passed as an anonymous tuple: .{ x, name }
  • std.debug.print returns void (best-effort, no error handling needed)
  • Writer-based printing returns errors — try it and flush() at the end
  • {q} and {qf} are 0.17-only; on 0.16 quote with {f} + std.zig.fmtId
#084

Building Strings

ziglings 006–007, 052–053

allocator.print for one-shots, std.mem.concat for joins, Writer.Allocating for incremental building.

One-shot and concat
const s = try gpa.print("a={d} b={s}", .{ a, b }); // 0.17: print lives on the allocator
defer gpa.free(s);

const joined = try std.mem.concat(gpa, u8, &.{ "foo", "bar" });
defer gpa.free(joined);
allocPrint — the 0.16 spelling
const s = try std.fmt.allocPrint(gpa, "a={d} b={s}", .{ a, b });defer gpa.free(s);

0.16 formats through the std.fmt namespace. 0.17 moved formatting onto the allocator as print. std.fmt.allocPrint still compiles on 0.17 — it is just not the spelling to write any more.

Incremental: Writer.Allocating (0.16)
var aw: std.Io.Writer.Allocating = .init(gpa);
defer aw.deinit();
try aw.writer.print("n={d}\n", .{ n }); // .writer is a FIELD, not a method
const owned = try aw.toOwnedSlice(); // take over the buffer
_ = owned;

aw.written() gives a borrowed view of what was written so far; toOwnedSlice() transfers ownership instead.

Rule of thumb: one formatted string → allocator.print (std.fmt.allocPrint is the old spelling); appending in a loop → Writer.Allocating or an ArrayList(u8) (see ArrayList).

#085

ArrayList

since 0.15ziglings 103

Growable array: unmanaged since 0.15 (allocator per call), .empty initialization since 0.16.

std.ArrayList(T) is a growable array. Since 0.15 only the unmanaged form exists — the allocator is passed to each method. Since 0.16 you initialize with .empty.

0.16 style
var list: std.ArrayList(u32) = .empty;
defer list.deinit(gpa);
try list.append(gpa, 1);
try list.appendSlice(gpa, &.{ 2, 3 });
list.items[0] = 9;
const owned = try list.toOwnedSlice(gpa); // caller owns the buffer
_ = owned;
methodnotes
append(gpa, v) / appendSlice(gpa, s)add at the end, !void
insert(gpa, i, v) / insertSlice(gpa, i, s)shift right, !void
pop()returns ?T since 0.15 — null when empty
orderedRemove(i)returns T, keeps order, O(n)
swapRemove(i)returns T, swaps in last element, O(1)
items / items.lenthe underlying slice / element count
clearRetainingCapacity()len = 0, memory kept for reuse
resize(gpa, n) / ensureTotalCapacity(gpa, n)grow (!void)
toOwnedSlice(gpa)hand over the exact-sized buffer
deinit(gpa)free the buffer
Do not hold *T pointers into list.items across append — growth may reallocate and invalidate them (see Pointer Pitfalls).
#086

HashMaps

AutoHashMap / StringHashMap (hashed) and the ArrayHashMap family (insertion order preserved).

std.AutoHashMap(K, V) derives hashing for any hashable K (ints, packed structs, ...); std.StringHashMap(V) hashes []const u8 keys. ArrayHashMap variants additionally keep insertion order.

Managed map (allocator stored)
var map: std.StringHashMap(u32) = .init(gpa);
defer map.deinit();
try map.put("a", 1);
if (map.get("a")) |n| std.debug.print("a={d}\n", .{ n }); // ?u32
if (map.getPtr("a")) |ptr| ptr.* += 1; // mutate in place
var it = map.iterator();
while (it.next()) |e|
    std.debug.print("{s}={d}\n", .{ e.key_ptr.*, e.value_ptr.* });
typenotes
std.AutoHashMap(K, V)auto-hashed keys
std.StringHashMap(V)[]const u8 keys
std.AutoArrayHashMap(K, V)+ insertion order, .keys() / .values()
std.StringArrayHashMap(V)string keys + order
std.array_hash_map.Auto / .String / .Customsince 0.16: ArrayHashMap family moved here (managed removed)
  • *Unmanaged variants take the allocator per call (like all containers since 0.15)
  • get returns ?V; getPtr returns ?*V for in-place mutation; getOrPut inserts-if-absent
  • Iterators yield key_ptr / value_ptr — dereference with .*
  • ArrayHashMap variants preserve insertion order; plain HashMap does not
#087

Sorting & Searching

std.mem.sort (stable block sort) and std.mem.sortUnstable (pdq) with a context-first comparator.

Sort structs by a field, descending
const Score = struct { name: []const u8, score: u32 };

fn byScoreDesc(_: void, a: Score, b: Score) bool {
    return a.score > b.score; // context comes FIRST (0.15+)
}

fn demo(items: []Score) void {
    std.mem.sort(Score, items, {}, byScoreDesc); // stable (block sort)
    std.mem.sortUnstable(Score, items, {}, byScoreDesc); // pdq, faster
}
functionnotes
std.mem.sort(T, items, ctx, lessThan)stable, in-place, O(n log n)
std.mem.sortUnstable(...)pdq sort, not stable, usually faster
std.sort.binarySearch(T, items, ctx, compareFn)requires sorted items — compare-callback shape varies, see std docs for your version

lessThan has signature fn (ctx, lhs, rhs) bool — return lhs < rhs for ascending order. Return > for descending as above.

#088

Bit Sets & Flag Sets

0.17 renamed the whole bit_set family and replaced initEmpty() with .empty. The rename is a hard break, not a deprecation.

0.160.17note
std.bit_set.IntegerBitSet(8)std.bit_set.Integer(8)fits in one int
std.bit_set.ArrayBitSet(u32, 16)std.bit_set.Array(u32, 16)same 2 args: mask type, then size
std.bit_set.StaticBitSet(12)std.bit_set.Static(12)comptime size
std.bit_set.DynamicBitSetUnmanagedstd.bit_set.Dynamicallocator-backed: no .empty literal
.initEmpty() / .initFull().empty / .fullvalue, not a call
EnumSet(E).initEmpty()EnumSet(E) = .emptysame rule in std.enums
count()count()not a rename — identical on both
0.17 spelling
const std = @import("std");
pub fn main() !void {
    var flags: std.bit_set.Integer(8) = .empty;      // 0.16: IntegerBitSet + initEmpty()
    flags.set(0);
    flags.set(3);
    var wide: std.bit_set.Array(u32, 16) = .full;    // 0.16: ArrayBitSet + initFull()
    wide.unset(9);
    var mask: std.bit_set.Static(12) = .empty;       // 0.16: StaticBitSet + initEmpty()
    mask.set(11);

    std.debug.print("mask={b} count={d} wide={d} static={d}\n", .{
        @as(u8, @bitCast(flags)), flags.count(), wide.count(), mask.count(),
    });

    const Flag = enum { read, write, exec };
    var perms: std.enums.EnumSet(Flag) = .empty;     // 0.16: EnumSet(Flag).initEmpty()
    perms.insert(.read);
    std.debug.print("perms={}\n", .{perms.contains(.read)});
}
verified · zig 0.17.0

Integer(N) is a packed struct over the mask int, so @bitCast gives you the integer. Array takes the mask type first, then the size — Array(16) is a compile error.

0.16 spelling
const std = @import("std");
pub fn main() !void {
    var flags: std.bit_set.IntegerBitSet(8) = std.bit_set.IntegerBitSet(8).initEmpty();
    flags.set(0);
    flags.set(3);
    var wide: std.bit_set.ArrayBitSet(u32, 16) = std.bit_set.ArrayBitSet(u32, 16).initFull();
    wide.unset(9);
    var mask: std.bit_set.StaticBitSet(12) = std.bit_set.StaticBitSet(12).initEmpty();
    mask.set(11);

    std.debug.print("mask={b} count={d} wide={d} static={d}\n", .{
        @as(u8, @bitCast(flags)), flags.count(), wide.count(), mask.count(),
    });

    const Flag = enum { read, write, exec };
    var perms: std.enums.EnumSet(Flag) = std.enums.EnumSet(Flag).initEmpty();
    perms.insert(.read);
    std.debug.print("perms={}\n", .{perms.contains(.read)});
}

Same program, same output, older names. bitCount() appears in neither: 0.16's IntegerBitSet answers no field or member function named 'bitCount' — the method has always been count().

  • .empty / .full are values: var s: std.bit_set.Integer(8) = .empty;
  • std.bit_set.Dynamic is allocator-backed and has no .empty value — construct it with an allocator
  • count(), set(), unset(), isSet() and toggle() keep the same names on both releases
  • EnumSet(E) uses the same .empty / .full rule and contains(key), insert(key), remove(key) on both
#089

std.mem Helpers

ziglings 097–098, 103

Compare, trim, split, find — with the 0.16 renames (trimStart, find*, new cut*).

helpernotes
eql / eqlIgnoreCaseslice equality
startsWith / endsWithprefix / suffix test
trim / trimStart / trimEndcut chars from both/start/end (renamed from trimLeft/trimRight since 0.16)
find / findLastindexOf* renamed since 0.16: indexOf → find, lastIndexOf → findLast
cut*split at the first match — new helpers since 0.16
splitScalar / splitSequence / tokenizeScalarlazy iterator over parts
replaceOwned / joinbuild new strings (allocate)
min / maxelement-wise min/max of slices
zeroes(T)a zeroed T value (comptime-known)
Everyday std.mem + std.fmt
const t = std.mem.trim(u8, "  hi \t", " \t"); // "hi"
if (std.mem.startsWith(u8, t, "hi")) {
    // ... - Zig has no /* block */ comments, only //
}

const n = try std.fmt.parseInt(u32, "4040", 10); // !u32
const f = try std.fmt.parseFloat(f64, "3.5"); // !f64
_ = .{ n, f };

splitScalar/tokenizeScalar return iterators — while (it.next()) |part| { ... }. tokenize skips empty parts, split yields them.

Run it: complete program
const std = @import("std");pub fn main() void {    const hay = "zig-zag";    const at = std.mem.indexOf(u8, hay, "-") orelse hay.len; // usize has no -1    const hits = std.mem.count(u8, hay, "g");    std.debug.print("{d} {d}\n", .{ at, hits });}
verified · zig 0.17.0
#090

Files & Dirs (std.Io)

since 0.16

Since 0.16 the file system lives behind the std.Io interface — every operation takes an io handle.

Since 0.16 the file system is part of the std.Io interface: std.Io.Dir and std.Io.File operations take an io handle (obtained from main(init)).

Read and write a file
// read, bounded to 1 MiB:
const bytes = try std.Io.Dir.cwd().readFileAlloc(
    io, "input.txt", gpa, .limited(1 << 20),
);
defer gpa.free(bytes);

// write:
var f = try std.Io.Dir.cwd().createFile(io, "out.txt", .{});
defer f.close(io);
try f.writeStreamingAll(io, "hi\n");

0.16 API — exact signatures may shift in patch releases; consult the std docs for your version.

  • std.Io.Dir.cwd() — current directory handle; openDir(io, path, .{}) for others
  • Directory iteration and recursive walk (selective walking since 0.16)
  • Preopens (WASI-style, since 0.16): directories are capabilities handed to the program
  • std.Io.File.stdout() / .stderr() — standard streams
#091

Process, Args, Env, Time & Random (0.16)

since 0.16

All process-level services are non-global since 0.16 — they arrive via main(init: std.process.Init).

Since 0.16 args, environ, spawning, time and randomness are non-global: they are capabilities passed to pub fn main(init: std.process.Init) ("Juicy main"). An empty pub fn main() is still legal.

Args and environ from init
pub fn main(init: std.process.Init) !void {
    const args = try init.minimal.args.toSlice(init.arena.allocator());
    const user = init.environ_map.get("USER") orelse "nobody";
    _ = user;
    std.debug.print("{d} args\n", .{args.len});
}
verified · zig 0.17.0
Running a child process
const result = try std.process.run(gpa, io, .{ .argv = &.{ "git", "status" } });
std.debug.print("{s}", .{result.stdout});
service0.16 access
argsinit.minimal.args.toSlice(init.arena.allocator())
environmentinit.environ_map.get("KEY") (.keys() / .values())
childrenstd.process.run(gpa, io, .{ .argv = ... })
timestd.Io.Clock / Timestamp / Duration types — Duration formats with {f}
randomnessmoved to the std.Io interface since 0.16 — see the io docs

For args+environ only, std.process.Init.Minimal is the lightweight variant of the init struct.

Section 16 of 21: Testing

4 entries

Built-in test framework: no dependencies, leak detection by default, fuzzing in the toolchain.

#092

Test Blocks

ziglings 102

Any test "..." { ... } block runs under zig test — assertions come from std.testing.

A test next to the code it tests
const std = @import("std");
const testing = std.testing;

fn add(a: i32, b: i32) i32 {
    return a + b;
}

test "add works" {
    try testing.expect(add(2, 2) == 4);
    try testing.expectEqual(@as(i32, 4), add(2, 2));
    try testing.expectFmt("4", "{d}", .{add(2, 2)});
}
verified · zig 0.17.0

Tests live next to the code — in the same file, or in a separate test file that imports it. zig test math.zig finds and runs every test block. Assertions return !void, so prefix them with try.

helperchecks
expect(cond)condition is true
expectEqual(expected, actual)deep equality (structs, arrays)
expectEqualStrings(a, b)string content + length
expectEqualSlices(T, a, b)element-wise slice equality
expectError(err, expr)expr fails with exactly err
expectApproxEqAbs / Relativefloat comparison with tolerance
expectFmt(expected, fmt, args)value formats to expected text

Note that unreferenced functions are not analyzed — a test that never calls f will not type-check f's body. Use refAllDecls (next entry).

#093

Running & Organizing

zig test for files, zig build test for projects, refAllDecls to force analysis.

A test root that pulls in everything
// src/all.zig
test {
    std.testing.refAllDecls(@This()); // force analysis of all decls
    _ = @import("parser.zig"); // and other files' tests
    _ = @import("json.zig");
}
  • zig test math.zig — run one file's tests
  • zig test src/all.zig — run a project via an aggregating root file
  • zig build test — through a test step in build.zig (see Test Step)
  • zig test --test-filter "json" src/all.zig — only matching test names
  • Name tests descriptively: test "json: parses empty object"

On failure the default runner prints the expression, expected vs actual, and a stack trace. Add --summary all (with zig build) for a per-step breakdown.

#094

Allocator-Aware Tests

ziglings 102

std.testing.allocator detects leaks per test — a leak fails the test with a stack trace.

A leak fails the test
test "leaks fail the test" {
    const a = std.testing.allocator;
    const buf = try a.alloc(u8, 16);
    _ = buf;
    // oops: no "defer a.free(buf);"
    // -> FAILS with a leak report (address + stack trace)
}
Arena for scratch data in tests
test "arena for scratch" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const s = try std.fmt.allocPrint(a, "{d}", .{42});
    try std.testing.expectEqualStrings("42", s);
}
Arena for scratch data — 0.17 formatting
test "arena for scratch" {
    var arena = std.heap.ArenaAllocator.init(std.testing.allocator);
    defer arena.deinit();
    const a = arena.allocator();
    const s = try a.print("{d}", .{42}); // 0.17: print is a method on the allocator
    try std.testing.expectEqualStrings("42", s);
}
verified · zig 0.17.0

On 0.17 formatting lives on the allocator, so there is no namespace and no allocator argument. The 0.16 spelling still compiles on 0.17 — it is deprecated, not deleted.

std.testing.allocator is a leak-checking wrapper around DebugAllocator (std/testing.zig:22 — pub var allocator_instance: std.heap.DebugAllocator(.{...})). expectEqual compares deeply for structs, unions and arrays — no per-field assertions needed.

std.testing.allocator is a leak-checking wrapper — on 0.17 that wrapper sits on SafeAllocator, not DebugAllocator (std/testing.zig:20 — pub var allocator_instance: std.heap.SafeAllocator). expectEqual compares deeply for structs, unions and arrays — no per-field assertions needed.

#095

Fuzzing

Fuzz targets are ordinary tests — zig build test --fuzz runs them coverage-guided.

A fuzz target (see std.testing.fuzz for your version)
test "parser never crashes on garbage" {
    try std.testing.fuzz(Context{}, fuzzParser, .{}); // coverage-guided: zig build test --fuzz
}

const Context = struct { max_len: usize = 64 };

fn fuzzParser(ctx: Context, smith: *std.testing.Smith) !void {
    var buf: [64]u8 = undefined;
    const n = smith.slice(buf[0..ctx.max_len]); // the fuzzer fills the buffer
    _ = parse(buf[0..n]) catch {}; // any crash = fuzz failure
}

The std.testing.fuzz API is still evolving — check the std docs for your version.

  • zig build test --fuzz — coverage-guided fuzzing (since 0.14)
  • Fuzz targets are normal test blocks; safe build modes turn memory errors into catchable crashes
  • Run it locally against your parser / decoder / any []const u8 consumer
  • 0.16 fuzzing improvements include:
  • AST smith — grammar-aware structured input generation
  • multiprocess fuzzing
  • infinite mode
  • crash dumps for reproduction

Section 17 of 21: Build System

7 entries

build.zig is Zig: declarative steps, cross-compilation and package management built in.

#096

Minimal build.zig

since 0.16

Target + optimize + one executable, installed with zig build, run with zig build run.

build.zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "app",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    b.installArtifact(exe);

    const run_cmd = b.addRunArtifact(exe);
    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

One file for both views: zig build with this build.zig succeeds on 0.16 and on 0.17.

The nested form is the form: .root_source_file, .target and .optimize go inside root_module = b.createModule(...), and that is what both supported compilers take. There is no older shape to fall back to — writing .root_source_file directly on b.addExecutable(.{ ... }) is rejected by 0.16 and by 0.17 with the same message: no field named 'root_source_file' in struct 'Build.ExecutableOptions'. 0.16 ExecutableOptions already has root_module, so the snippet above is not a 0.17 migration; it is the API both releases share.

  • zig build — default step: compile and install to zig-out/bin
  • zig build run — run the run step defined above
  • --release=fast — optimized build without editing anything
#097

Steps, Options & Artifacts

Custom -D options, named steps, and the artifact kinds the build graph understands.

Options and steps
const level = b.option(u32, "level", "compression level 0-9") orelse 6; // try: zig build -Dlevel=9
const target = b.standardTargetOptions(.{}); // try -Dtarget=x86_64-windows-gnu
const optimize = b.standardOptimizeOption(.{}); // try --release=fast
const t = b.step("test", "Run tests"); // try: zig build test
_ = .{ level, target, optimize, t };
invocationeffect
zig builddefault step: install artifacts
zig build runrun a custom step
zig build test --summary alltest step + full failure summary
--release=safe|fast|smalloptimize mode (Debug if unset)
-Doptimize=ReleaseSafesame, via the standard option
-Dtarget=x86_64-windows-gnucross-compile target triple
-Dlevel=9your own b.option values
--prefix ./outinstall directory instead of zig-out
Path-valued options — 0.17
const o = b.addOptions(); // try: zig build -Dconfig_file=./x.inio.addOptionPath("config_file", b.path("config.ini")); // tracked file: both compilerso.addOptionPathDirectory("data_dir", b.path("data")); // 0.17 onlyo.addOptionPathUntracked("scratch", b.path("tmp")); // 0.17 only

COMPILE FACT: 0.16 rejects the last two lines — no field or member function named 'addOptionPathDirectory' in 'Build.Step.Options', and the same for addOptionPathUntracked. addOptionPath and addOption(u32, "level", 6) compile on both compilers, so they belong to every view.

Optimize mode in build.zig — 0.16 spelling
const optimize: std.builtin.OptimizeMode = .ReleaseSafe; // 0.16: the only spelling
Optimize mode in build.zig — 0.17 spelling
const optimize: std.lang.Optimize = .safe; // 0.17: the new home of the mode enum

Naming inside build.zig: 0.17 moved the enum to std.lang.Optimize (std.builtin.OptimizeMode is now an alias) and renamed the members to debug / safe / fast / small. std.lang does not exist on 0.16 at all, and 0.16 rejects -Doptimize=safe with Expected -Doptimize to be of type builtin.OptimizeMode. --release=safe|fast|small is unchanged — it works on both. -Doptimize=ReleaseSafe works on both as well: 0.17 keeps the Release* names as deprecated aliases, so the table above belongs to every view.

  • Artifacts: b.addExecutable(...) / b.addLibrary(...) / b.addObject(...)
  • b.installArtifact(artifact) attaches it to the default install step
  • b.addRunArtifact(...) runs executables and tests as a build step
  • b.default_step — what plain zig build runs
#098

Modules & Dependencies

Wire multi-file projects with createModule + imports; fetch packages via build.zig.zon.

Two modules, one import
const lib_mod = b.createModule(.{
    .root_source_file = b.path("src/lib.zig"), // try: one module per source file
    .target = target,
    .optimize = optimize,
});
const exe_mod = b.createModule(.{
    .root_source_file = b.path("src/main.zig"), // try: @import("lib") from main.zig
    .target = target,
    .optimize = optimize,
    .imports = &.{
        .{ .name = "lib", .module = lib_mod },
    },
});
_ = .{ lib_mod, exe_mod };
// in main.zig:  const lib = @import("lib");
Package dependency from build.zig.zon
// build.zig.zon:
//   .dependencies = .{ .lib = .{ .url = "https://...", .hash = "..." } },
const dep = b.dependency("lib", .{});
exe.root_module.addImport("lib", dep.module("lib"));
// add deps with:  zig fetch --save <url-or-tarball>
The package root — 0.16 spelling
const dir = b.build_root; // try: zig build — the directory holding build.zig_ = dir;

COMPILE FACT: 0.17 removed the field — no field named 'build_root' in struct 'Build'. 0.16 Build.build_root is a Cache.Directory naming the directory that holds build.zig.

The package root — 0.17 spelling
const dir = b.root; // try: zig build — the package root_ = dir;

COMPILE FACT: 0.16 rejects it — no field named 'root' in struct 'Build'. 0.17 Build.root is a Cache.Path; b.path(...) resolves relative to it on both compilers.

Several paths — 0.16 spelling
const files = &.{ b.path("main.zig"), b.path("build.zig") }; // try: zig build_ = files;

CURATION, not a break: this slice of LazyPath compiles on 0.17 too. It is the 0.16 view because 0.16 has no list helper — b.pathList does not exist there.

Several paths — 0.17 spelling
const files = b.pathList(&.{ "main.zig", "build.zig" }); // try: zig build_ = files;

COMPILE FACT: 0.16 rejects it — no field or member function named 'pathList' in 'Build'. 0.17 pathList returns []const LazyPath, each entry resolved like b.path.

zon fieldnotes
.nameenum literal since 0.14: .my_project
.versionsemver string, e.g. "0.1.0"
.fingerprintpackage identity hash (0.14+)
.minimum_zig_versionoldest Zig that can build this
.dependenciesmap of { .url, .hash } (or local path) deps
.pathsfiles/dirs included when the package is used
#099

Linking & C Files

link libc, system libraries, include paths, .c sources — and translate-c for headers.

Mixing C into a Zig build
exe.root_module.link_libc = true; // -lc
exe.root_module.linkSystemLibrary("sdl2", .{}); // -lSDL2
exe.root_module.addIncludePath(b.path("include")); // -I
exe.root_module.addCSourceFiles(.{
    .files = &.{ "vendor/foo.c", "vendor/bar.c" },
    .flags = &.{},
});

These calls live on the Module, not on the Compile step: exe.root_module. Compiled on both toolchains — exe.linkLibC() is rejected by 0.16 and by 0.17 with no field or member function named 'linkLibC' in 'Build.Step.Compile', and linkSystemLibrary, addIncludePath and addCSourceFiles are not Compile members on either compiler either. linkSystemLibrary takes THREE arguments (name, options) on both. Not a split: one spelling for both views.

translate-c for headers
const tc = b.addTranslateC(.{
    .root_source_file = b.path("src/bindings.h"), // try: header to Zig bindings
    .target = target,
    .optimize = optimize,
});
exe.root_module.addImport("c", tc.createModule());

Not a split: b.addTranslateC has the identical signature on both compilers (options: Step.TranslateC.Options → *Step.TranslateC; 0.17 Build.zig:949, 0.16 Build.zig:1115) and this snippet builds on 0.16 and on 0.17. What moved is @cImport: 0.17 answers invalid builtin function: '@cImport', so this build-based flow is the way to bind a header on both views. There is no fetch-based replacement to migrate to — b.addTranslateC is still the API 0.17 exposes.

#100

Test Step

The standard zig build test recipe: addTest + addRunArtifact + a named step.

Standard test step
const tests = b.addTest(.{ .root_module = mod }); // try: zig build test
const run_tests = b.addRunArtifact(tests); // try: zig build test runs this
const t = b.step("test", "Run unit tests"); // try: zig build test --summary all
t.dependOn(&run_tests.step);
Forwarding `--` args — 0.16 spelling
const run = b.addRunArtifact(exe); // try: zig build run -- --flagif (b.args) |args| run.addArgs(args); // 0.16: the args after --const s = b.step("run", "Run the app"); // try: zig build run -- --flags.dependOn(&run.step);

COMPILE FACT: 0.17 removed the field — no field named 'args' in struct 'Build'. On 0.16 b.args is the ?[]const []const u8 after --, and run.addArgs(args) forwards it.

Forwarding `--` args — 0.17 spelling
const run = b.addRunArtifact(exe); // try: zig build run -- --flagrun.addPassthruArgs(); // 0.17: reads -- from the CLI, takes NO argumentsconst s = b.step("run", "Run the app"); // try: zig build run -- --flags.dependOn(&run.step);

COMPILE FACT: 0.16 rejects it — no field or member function named 'addPassthruArgs' in 'Build.Step.Run'. It takes ZERO arguments: run.addPassthruArgs(.{ "--x" }) fails on 0.17 with member function expected 0 argument(s), found 1. Run.zig documents that using it makes the step count as having side effects, which disables caching for it.

  • addTest analyzes every test block reachable from the module root
  • Force analysis of leaf decls with std.testing.refAllDecls in your code (see Testing)
  • Run: zig build test; add --summary all for details
  • zig build test --fuzz — fuzz mode (see Fuzzing)
  • Unit-test timeouts are available as an option since 0.16

The test step depends on the same module graph as your exe — tests compile with the target and optimize settings of the module they test. The root Module of a Compile step must be created with a known target: leave it out and BOTH compilers abort with the root Module of a Compile step must be created with a known 'target' field.

#101

Configure Cache Hygiene

What makes zig build re-run its configure phase, which calls poison that cache, and the lazy alternative.

0.17 splits zig build into a configure phase (build.zig runs, the step graph is described) and a make phase (a separate maker process executes it). The configuration is cached, so an unchanged zig build skips the configure phase entirely. Anything in build.zig that observes the host breaks that: std.Build documents findProgram verbatim — "Calling this function poisons the configuration cache, so it is only appropriate when the existence of the program or its output needs to be observed by configuration logic. For more information, see Graph.CachePoison documentation." A poisoned configuration cannot be reused: the maker process deletes the build configuration file when it ingests it, so every later zig build re-runs the whole configure phase. Keeping the cache pure is what makes repeated zig build invocations fast.

There is no configure cache on 0.16, so nothing on this page applies to it. 0.17 introduced the configure/make split; 0.16 runs build.zig and executes the graph in one pass. Measured in the 0.16 stdlib: Graph.CachePoison, poisonCache, cache_poison, and the dependOnFileContents family appear in no 0.16 source file. So b.findProgram costs you nothing special on 0.16 — every zig build re-runs build.zig regardless. Everything below is 0.17 behaviour: 0.17 answers no field named 'cache_poison' in struct 'Build.Graph' and no field or member function named 'dependOnFileContents' in 'Build'.

Host observation — 0.16 spelling
const scdoc = b.findProgram(&.{"scdoc"}, &.{}) catch ""; // try: 0.16 answers FileNotFound_ = scdoc;

COMPILE FACT: 0.17 rejects this call shape — member function expected 1 argument(s), found 2. 0.16 has no configure cache at all: Graph.CachePoison, poisonCache and the dependOn* configure-dependency calls exist in NO 0.16 source, so on 0.16 there is nothing to poison and nothing to hygiene about.

Host observation — 0.17 spelling
const scdoc = b.findProgram(.{ .names = &.{"scdoc"} }) orelse ""; // poisons: try --summary allconst where = b.findProgramLazy(.{ .names = &.{"scdoc"} }); // LazyPath: try zig build_ = .{ scdoc, where };

COMPILE FACT: 0.16 rejects both lines — member function expected 2 argument(s), found 1 for findProgram, and no field or member function named 'findProgramLazy' in 'Build'. findProgram searches search-prefixes and PATH in the configure phase and calls graph.poisonCache(). findProgramLazy returns a LazyPath and defers the search to the make phase, so it observes nothing at configure time and keeps the cache pure. Prefer it whenever you only need the path.

Tracking a dependency instead of poisoning
b.dependOnFileContents(b.path("build.zig")); // re-run configure when this file changesb.dependOnDirectoryContents(b.path(".")); // ... or when this directory changes

COMPILE FACT: 0.16 has none of these — no field or member function named 'dependOnFileContents' in 'Build'. Build.zig calls them "an alternative to Graph.poisonCache that avoids making every invocation of zig build into a cache miss". The four are dependOnFileContents, dependOnFileMetadata, dependOnDirectoryContents, dependOnDirectoryMetadata; a content dependency re-runs configure only when the bytes change, a metadata dependency also reacts to inode and mtime.

Auditing a build.zig for poisoning
b.graph.cache_poison = .disallowed; // try: zig build — panics on the first poisoning

COMPILE FACT: 0.16 has no such field — no field named 'cache_poison' in struct 'Build.Graph'. Graph.CachePoison is pure / poisoned / disallowed / ignored; with .disallowed, poisonCache answers @panic("cache poisoned"), and with .ignored it only logs ignoring cache poisoning.

  • Poisons the cache: b.findProgram — it reads search prefixes and PATH, then calls graph.poisonCache()
  • Counted in 0.17 std: findProgram is the ONLY Build call that calls poisonCache() (Build.zig:1625). Everything else that poisons is your own b.graph.poisonCache() call
  • Does NOT poison: b.findProgramLazy — a LazyPath, the search happens in the make phase
  • Track it instead of poisoning: dependOnFileContents, dependOnFileMetadata, dependOnDirectoryContents, dependOnDirectoryMetadata
  • A poisoned configuration is deleted by the maker process, so the configure phase re-runs on every invocation
  • Audit a build.zig with b.graph.cache_poison = .disallowed — the next poisoning panics with cache poisoned instead of silently costing you a cache miss
#102

Read The Build Cache

since 0.17

Four build-invocation flags that show what the configure phase decided — three of them are new in 0.17.

Flag0.160.17
zig build --print-configurationunrecognized argumentrenders the whole configuration as ZON
zig build --print-configuration-pathunrecognized argumentprints the cache file holding it
zig build --cache-poison=<mode>unrecognized argumentpure / poisoned / disallowed / ignored
zig build --listen=-unrecognized argumentbuild server protocol on stdio
zig build --watch / -fincrementalworksworks
zig cache-cat <manifest>no such commandprints a cache manifest as ZON
Configuration, its path, and the manifest behind a hit
zig build --print-configuration | head -8.{    .search_prefixes = .{},    .default_step = 0,    .top_level_steps = .{        .install = 0,        .uninstall = 1,    },zig build --print-configuration-path.../.zig-cache/local/c/b35ff9b41fad3e94a5a76e8047c13ed5zig cache-cat .zig-cache/h/16e4e8a35d47292a66ce4b312d2942d7.{    .input_hash = "16e4e8a35d47292a66ce4b312d2942d7",    .files = .{        .{ .size = 11021, .inode = 4159600, .mtime = 1790892153000000000,           .digest = "15365cbf3e86531c4093be7a9cd9ee4b", .prefix = 1, .path = "std/std.zig" },    },    .discovered_hash = "...",}

cache-cat reads the manifest files in .zig-cache/h/: every input file with its size, inode, mtime and digest, plus the hash Zig recomputed from them. When a rebuild surprises you, this is the file that says why.

`--watch` and `-fincremental` are not 0.17 features:Both flags exist on 0.16 too — measured: zig build --watch and zig build -fincremental both run on 0.16.0 on this box. What the 0.17 release notes describe is incremental compilation doing its job on x86_64-linux, not a flag arriving. Do not write if version >= 0.17 around either flag.

Section 18 of 21: C Interop

5 entries

Call C, export Zig, translate headers, and cross-compile C itself — no glue layer needed.

#103

C Types & [*c] Pointers

ziglings 093–094

c_int and friends for C-width integers; [*c]T for nullable C pointers of unknown length.

Zig typeC equivalent
c_char, c_short, c_int, c_long, c_longlongchar, short, int, long, long long
c_uint, c_ushort, c_ulong, c_ulonglongunsigned variants
c_longdoublelong double
boolbool (C99 _Bool)
usizesize_t
f32 / f64float / double (fixed width)

[*c]T is the C pointer: nullable, allowzero, coerces in both directions with [*]T, [*:0]T and ?[*]T, and has unknown length (no indexing, no .len). A null check works through optional coercion: if (cptr) |p| ....

C pointers in practice
const std = @import("std");

extern fn strlen(s: [*c]const u8) usize;

fn safeLen(s: [*c]const u8) usize {
    if (s) |p| return strlen(p); // null check via optional coercion
    return 0;
}

pub fn main() void {
    const cstr: [*:0]const u8 = "hello";
    const cptr: [*c]const u8 = cstr;
    std.debug.print("strlen={d} span={s}\n", .{ safeLen(cptr), std.mem.span(cstr) });
}
verified · zig 0.17.0

Untagged: runs on 0.16 and on 0.17, printing strlen=5 span=hello. [*c]T, its optional coercion and std.mem.span are unchanged by the migration.

std.mem.span(cstr) converts a [*:0]const u8 into a []const u8 by counting to the sentinel — the bridge between C strings and Zig slices.

#104

Calling C Functions

ziglings 093–094

Declare extern fns yourself, link libc, done — headers optional when you import a translate-c module.

extern declarations
extern "c" fn puts(s: [*:0]const u8) c_int;
extern fn abs(x: c_int) c_int; // "c" implied when linking libc
extern "c" fn printf(fmt: [*:0]const u8, ...) c_int; // variadic

pub fn main() void {
    _ = puts("hello from zig");
    _ = abs(-42);
    _ = printf("n=%d\n", @as(c_int, 7));
}
verified · zig 0.17.0
  • Library name optional: extern fn ... defaults to the C ABI of the linked libc
  • Variadic: ... in the parameter list, like C
  • Functions passed into C use the C calling convention: fn f() callconv(.c) void
Linking
// build.zig — linking is a property of the module, not of the executable step
const mod = b.createModule(.{
    .root_source_file = b.path("main.zig"),
    .target = target,
    .optimize = optimize,
    .link_libc = true, // the build.zig spelling of -lc
});
mod.linkSystemLibrary("m", .{}); // libm, SDL2, ... anything pkg-config finds

// command line:
//   zig build-exe main.zig -lc
#105

Exporting Zig for C

export fn emits C-ABI symbols; extern struct/union/enum fix the ABI layout; callbacks via callconv(.c).

Exported functions and symbol control
export fn add(a: c_int, b: c_int) c_int {
    return a + b; // symbol "add" lands in the object file
}

fn mul(a: c_int, b: c_int) callconv(.c) c_int {
    return a * b;
}

comptime {
    @export(&mul, .{ .name = "my_mul" }); // custom symbol name
}

Untagged: compiles on 0.16 and on 0.17 — @export and callconv(.c) are unchanged. The comptime block is analyzed, so the symbol name is checked for real.

extern struct, extern union and extern enum(c_int) guarantee C ABI field layout — use them for types shared across the boundary. Plain Zig structs may reorder/pad differently.

Passing a Zig callback into C
const std = @import("std");

const Callback = *const fn (ctx: ?*anyopaque, n: c_int) callconv(.c) void;
extern "c" fn register(cb: Callback) void;

fn onEvent(ctx: ?*anyopaque, n: c_int) callconv(.c) void {
    _ = ctx;
    std.debug.print("event {d}\n", .{n});
}

pub fn init() void {
    register(onEvent);
}

Untagged: compiles on 0.16 and on 0.17. The import is part of the snippet — without it both compilers answer use of undeclared identifier 'std'. Hand-compiled with a main that calls onEvent: prints event 3 on both.

  • zig build-lib lib.zig — static library
  • zig build-lib -dynamic lib.zig — shared library
  • The C header for your exports must be written by hand
#106

Headers: translate-c

since 0.16

@cImport is gone in 0.17 — translate headers in build.zig and import them as a module.

  • 0.160.17@cImport is removed, not deprecated. 0.17 answers invalid builtin function: '@cImport'.→ Translate the header in build.zig with b.addTranslateC and @import the module tc.createModule() returns.

COMPILE FACT, not curation: the 0.17 compiler rejects the old spelling outright. b.addTranslateC itself did not move — it has the same signature and the same Options fields on 0.16 and on 0.17.

@cImport — 0.16 only
const c = @cImport({    @cInclude("stdio.h");});const puts = c.puts;   // a C symbol, straight from the header

COMPILE FACT: 0.16 compiles this; 0.17 answers invalid builtin function: '@cImport'. Deprecated in 0.16, deleted in 0.17 — the builtin is gone, so there is no 0.17 spelling of it.

Translate a header in build.zig
// build.zig:const tc = b.addTranslateC(.{    .root_source_file = b.path("vendor/sqlite3.h"),    .target = target,    .optimize = optimize,});const mod = b.createModule(.{    .root_source_file = b.path("main.zig"),    .target = target,    .optimize = optimize,});mod.addImport("c", tc.createModule());

Untagged: zig build accepts this body on 0.16 and on 0.17. Curation, not a break — the site teaches the build-graph form in both views because both compilers take it.

main.zig — use the translated module
const c = @import("c");pub fn main() void {    const p = c.vend_point{ .x = 1, .y = 2.5 }; // extern struct, straight from the header    _ = p;    _ = c.vend_add(2, 3); // static inline C function, translated for free}

History. @cImport was the in-file spelling through 0.15. 0.16 added b.addTranslateC and deprecated the builtin; 0.17 deleted the builtin, so the tab above is the last release that compiles it. Nothing else about translate-c moved.

  • One-shot CLI: zig translate-c vendor/sqlite3.h > bindings.zig, then @import("bindings.zig") — works on 0.16 and on 0.17
  • Include paths and defines can be given on the translate-c step
  • Vendoring the generated bindings.zig avoids a build step entirely
@cImport compiles on 0.16 (see the 0.16 tab) and is removed in 0.17: invalid builtin function: '@cImport'. That is a compile fact, not a house style — one @cImport anywhere in a 0.17 build stops the build.
#107

zig cc — C/C++ Toolchain

Zig ships a full clang-based C/C++ compiler with cross-compilation and bundled libc targets.

Compile C with zig cc
zig cc main.c -o main              # drop-in clang/gcc replacementzig cc -target aarch64-linux-gnu main.c -o main  # instant cross-compilezig c++ main.cpp -o main           # C++ too

All three lines verified on 0.16.0 and on 0.17.0: each produced a binary that printed its message.

zig cc --version — 0.16
zig cc --versionclang version 21.1.0

The Clang 0.16.0 ships. Read from zig cc --version, not from the release notes.

zig cc --version — 0.17
zig cc --versionclang version 22.1.8

The Clang 0.17.0 ships — the release notes say 22.1.8 and zig cc --version agrees.

  • libc headers and libraries are bundled: musl, glibc, mingw-w64 — no system toolchain required
  • Same target-triple syntax as zig build -Dtarget=...
  • Ideal for building C dependencies and Makefile-free builds
  • Flags are clang-compatible: -I, -L, -l, -static, ...
Cross-compile one C file, two targets
# build a C library once, for two targets, no Docker:zig cc -c -Iinclude vendor/foo.c -target x86_64-linux-gnu -o foo-linux.ozig cc -c -Iinclude vendor/foo.c -target aarch64-macos-gnu -o foo-mac.o

Both lines verified on 0.16.0 and on 0.17.0 — each emitted its object file with no system toolchain.

Section 19 of 21: Concurrency

5 entries

Threads, locks and atomics — plus the 0.16 std.Io interface that replaced async/await.

#108

Threads

ziglings 104–105

std.Thread.spawn with any function and argument tuple; join or detach; shared state is your job.

Spawn + join with a context struct
const Job = struct { n: u32, out: u32 = 0 };

fn worker(job: *Job) void {
    job.out = job.n * 2;
}

pub fn main() !void {
    var job: Job = .{ .n = 21 };
    const t = try std.Thread.spawn(.{}, worker, .{&job});
    t.join(); // block until done (or: t.detach())
    std.debug.print("{d}\n", .{job.out}); // 42
}
verified · zig 0.17.0
operationnotes
std.Thread.spawn(.{}, f, .{args})returns !Thread — options struct first
t.join()block until the thread finishes
t.detach()let it run free; never join it
std.Thread.current()handle for the calling thread
std.Thread.getCpuCount()!usize — hardware parallelism
Data races are UB. Sharing mutable state across threads requires synchronization (locks) or atomics — the compiler will not stop you, so route anything shared through one of the next two entries.
#109

Mutex, Condition & Friends

The std.Io synchronization primitives: Mutex, Condition, Event, Semaphore, RwLock — every operation takes an io handle.

primitiveoperations
std.Io.MutextryLock() / lock(io) / lockUncancelable(io) / unlock(io); initialize with .init
std.Io.Conditionwait(io, &mutex) / signal(io) / broadcast(io) / waitTimeout(...)
std.Io.Eventwait(io) / set(io) / reset() / isSet(); states .unset / .waiting / .is_set
std.Io.Semaphorewait(io) / post(io) / waitUncancelable(io)
std.Io.RwLocklock(io) / unlock(io) / lockShared(io) / unlockShared(io) / tryLockShared(io)
Guard pattern: mutex next to its data
const Counter = struct {
    mu: std.Io.Mutex = .init,
    n: u32 = 0,

    fn bump(self: *Counter) void {
        self.mu.lockUncancelable(io);
        defer self.mu.unlock(io); // always unlock, even on early return
        self.n += 1; // protected critical section
    }
};

std.Io.Mutex is an extern struct with a state field, so it initializes with .init, not .{}. lock(io) returns Cancelable!void; lockUncancelable(io) is the infallible form, which is what a defer-based guard wants.

Event: one-shot done signal
var done: std.Io.Event = .unset;

fn work() void {
    defer done.set(io);
    // ... do the work ...
}

// another task:
done.waitUncancelable(io); // blocks until set()

std.Io.Event is an enum(u32) — initialize it with .unset, not .{}. It replaces the std.Thread.ResetEvent that older Zig documentation describes; that name does not exist in 0.16 or 0.17.

#110

Atomics

std.atomic.Value(T) wraps one value with explicit memory ordering; raw @atomic* builtins below it.

Stop flag across threads
var stop: std.atomic.Value(bool) = .init(false);

fn worker() void {
    while (!stop.load(.acquire)) {
        // ... work chunk ...
    }
}

// main thread:
stop.store(true, .release); // signal shutdown
std.atomic.Value(T) opcall
createstd.atomic.Value(T).init(v)
read.load(.acquire)
write.store(v, .release)
exchange.swap(v, .seq_cst)
read-modify-write.rmw(.Add, x, .seq_cst)
raw builtinpurpose
@atomicLoad(T, ptr, order)atomic read
@atomicStore(T, ptr, v, order)atomic write
@atomicRmw(T, ptr, op, v, order)atomic read-modify-write
@cmpxchgStrong / @cmpxchgWeakcompare-and-swap (weak may spuriously fail)
@fence(order)standalone memory barrier
  • Memory orders: .monotonic (relaxed), .acquire, .release, .acq_rel, .seq_cst
  • Default to .seq_cst; relax only with profiling evidence
  • .monotonic for counters, .acquire/.release pairing for flag hand-offs
#111

std.Io: The Async Story (0.16)

since 0.16

async/await keywords are gone — concurrency is an interface (std.Io) with pluggable implementations.

History callout:The async / await / suspend / resume keywords were removed since 0.14. Since 0.16, I/O concurrency is expressed through the std.Io interface instead — an io handle flows through your program.
abstractionrole
std.Io.Futureone task started from a function; await its result
std.Io.Groupmany tasks; await or cancel all of them
std.Io.Queue(T)MPMC channel between tasks
std.Io.Batchbatch many operations, submit together
std.Io.Selectwait on several operations at once
implementationnotes
std.Io.Threadeddefault — operations block on a thread pool
std.Io.Eventedexperimental green threads
std.Io.Uring / Kqueue / Dispatchproof-of-concept backends
std.Io.failingalways fails — tests, no-IO builds
Illustrative shape (simplified)
// SIMPLIFIED - the 0.16 std.Io API is evolving:
// consult the std docs for your exact version.
const fut = try io.async(work, .{ arg }); // start a task
const out = try fut.await(io); // join it

// many tasks: std.Io.Group
//   g.async(io, work, .{...}) for each, then g.await(io) / g.cancel(io)
  • -fsingle-threaded — compile assuming one thread (enables optimizations, disables thread APIs)
  • -fno-single-threaded — force the opposite
  • Which backend runs is configured per root module — see the std.Io docs for your version
#112

Choosing a Tool

CPU parallelism → threads; I/O concurrency → std.Io; signaling → events; counters → atomics.

you needreach for
CPU parallelismstd.Thread (+ locks / atomics)
I/O concurrencystd.Io — Future / Group / Queue(T)
simple signalingstd.Io.Event or std.Io.Condition
counters / stop flagsstd.atomic.Value(T)
per-task scratch memoryone ArenaAllocator per task

Start with std.Thread for CPU-bound work. std.Io.Threaded gives I/O concurrency without changing your threading model; std.Io.Evented scales to many concurrent I/O operations on few threads.

Ziglings exercises 085–095 teach the removed async/await keywords — treat them as historical. Ziglings exercises for the new std.Io interface are still pending.

Section 20 of 21: Gotchas & Tips

8 entries

Where Zig bites: UB, undefined, version churn — and the philosophy behind the rules.

#113

Safety Checks vs UB

Debug and ReleaseSafe panic with a trace; ReleaseFast turns failed checks into UB; ReleaseSmall mostly drops them.

checkDebug / ReleaseSafeReleaseFastReleaseSmall
array/slice boundspanic + traceUBoff
integer overflowpanic + traceUBwrapping (off)
.? on nullpanic + traceUBoff
unreachable reachedpanic + traceUBoff
division by zeropanic + traceUBoff
cast truncation (@intCast)panic + traceUBoff

Rule: develop and test in Debug or ReleaseSafe, ship ReleaseFast only with solid tests and coverage. ReleaseSmall trades most safety checks for binary size (overflow wraps silently).

  • unreachable is a promise to the optimizer — keep it true in every mode
  • @intCast and .? are checked in safe modes, unchecked elsewhere
  • Out-of-range @intFromFloat is UB — range-check before converting
#114

undefined & Uninitialized

undefined means "no value" — reading it is UB in every build mode (0xAA fill makes it visible in Debug).

Declare now, initialize before use
var buf: [64]u8 = undefined; // declared, not initialized
@memset(&buf, 0); // MUST write before reading

// const x: u32 = undefined;
// _ = x + 1;   // UB — and the compiler catches this particular shape at comptime:
               // "use of undefined value here causes illegal behavior"

A directly-assigned undefined that you then read is a compile error, not a runtime surprise. The dangerous form is the one the compiler cannot see: var v: T = undefined; passed to a function that reads a field you never wrote. That one compiles, and the Debug 0xAA fill is the only reason it fails loudly.

Reading undefined is UB in every mode. Debug fills with 0xAA so the damage shows up as crashes or absurd values instead of silent luck.
  • Defer-init pattern: var v: T = undefined; then assign all fields before first read
  • Struct literals: initialize every field or give fields defaults — no partial init
  • @memset(ptr, 0) bulk-initializes a buffer
  • Legit uses: buffers a function will fully overwrite, or values the OS/writer fills before you read
#115

Pointer Pitfalls

Dangling after growth, misaligned casts, and the four pointer spellings people mix up.

Invalidation after growth
var list: std.ArrayList(u32) = .empty;
defer list.deinit(gpa);
try list.append(gpa, 1);
const first: *u32 = &list.items[0];
try list.append(gpa, 2); // may reallocate items
// 'first' may now DANGLE - retake &list.items[0]
  • Alignment: casting to a stricter alignment via @ptrCast needs @alignCast — misaligned access is UB
  • Use-after-free: reading after free (see Lifetime Rules)
  • []T (len known) vs [*]T (many, unknown len) vs [*c]T (C) vs *T (exactly one) — coerce deliberately
  • Capture semantics: for (items) |item| gives a copy; |*item| gives *T so writes stick
Copy vs by-reference capture
for (items) |item| {          // item is a copy: writes are lost
    var copy = item;
    copy += 1;
}
for (items) |*item| {         // item: *T - mutations persist
    item.* += 1;
}
#116

Language Surprises

Small rules that trip up newcomers: comptime_int locals, bool-only conditions, mandatory else, no shadowing.

  • ! negates a bool; ~ is bitwise-not for integers — there is no ~ for bools
  • No x++ / x--: write x += 1
  • if conditions must be bool — no truthy integers or pointers
  • var x = 1; is a compile error at runtime scope: the literal is comptime_int, so annotate the type
  • Indexing takes usize — cast with @intCast (or @as) first
  • Shadowing is forbidden: an inner x cannot hide an outer x
  • Unused variables, parameters and errors are compile errors — discard with _ = x;
  • Blocks are expressions: an if used as a value requires else
  • switch must be exhaustive (add else => to cover the rest)
Unannotated integer literal
var x = 1; // ERROR: '1' is comptime_int, runtime vars need a type
var y: i32 = 1; // OK
Value-context if requires else
const maybe: ?u32 = null;
const v = if (maybe) |n| n else 0; // else is mandatory here
const s = switch (maybe) { .some => 1, .none => 0 }; // exhaustive too
#117

NaN Equality Changed

since 0.17

Same code, different answer: mem.eql(f64, …) on two NaNs says false on 0.17 and true on 0.16.

Two NaNs, one byte pattern
const std = @import("std");
pub fn main() !void {
    const a = [_]f64{std.math.nan(f64)};
    const b = [_]f64{std.math.nan(f64)};
    std.debug.print("eql={}\n", .{std.mem.eql(f64, &a, &b)});
    std.debug.print("findDiff={?}\n", .{std.mem.findDiff(f64, &a, &b)});
}
verified · zig 0.17.0

mem.eql compares bytes. Two NaNs can share the same byte pattern, so 0.16 called them equal. 0.17 fixes it to follow IEEE: NaN is not equal to anything, including an identical NaN.

call0.160.17
mem.eql(f64, &a, &b) with both a and b NaNtruefalse
mem.findDiff(f64, &a, &b)null (no difference)0 (differs at index 0)
Do not compare floats by bytes:mem.eql on floats was never a value comparison — it compares memory. If your code relied on the 0.16 answer, the fix is not a byte compare on 0.17 either: test NaN with std.math.isNaN, compare values with == (which is false for NaN on both compilers), and use mem.eql for integers, bytes and booleans.
#118

Version Migration Traps (0.15 → 0.16 → 0.17)

since 0.16

The rename-and-remove list that breaks older code: containers, mem helpers, IO, allocators, bit sets, @cImport, @Type, build.zig.

0.15 and earlier0.16
var l = ArrayList(T).init(gpa)var l: ArrayList(T) = .empty + allocator per call
std.heap.GeneralPurposeAllocatorstd.heap.DebugAllocator
std.mem.trimLeft / trimRighttrimStart / trimEnd
std.mem.indexOf*std.mem.find* (indexOf → find, lastIndexOf → findLast)
@cImport({ @cInclude(...) })b.addTranslateC + module import
@Type(...)@Int, @Float, @Array, @Pointer, ... type builders
std.process.argsAlloc()init.minimal.args.toSlice(init.arena.allocator())
std.fs.cwd() / std.fsstd.Io.Dir / std.Io.File with an io handle
aw.writer() method callaw.writer field access
std.Thread.Poolremoved — use std.Io
managed ArrayHashMapstd.array_hash_map.Auto / .String / .Custom
global args / envmain(init) only — init.minimal.args, init.environ_map
Writer.Allocating.writer is a field, not a method — aw.writer() is a compile error; write aw.writer.print(...). Full details: the 0.16.0 release notes.

Every row below is a compiler-verified 0.16 → 0.17 split: the left form was compiled with /bin/zig_legacy (0.16.0) and the right form with /bin/zig (0.17.0) on this box. Rows marked *silent* compile on 0.17 today and are the dangerous ones — they break in a later release.

0.160.17how it fails
[1]u8{ 0xAA } ** 16@splat(0xAA)syntax — ** is not an operator
@splat(4, 2.0)@splat(2.0)expected 1 argument, found 2 — and 0.16 rejects it too
errdefer |e| cleanup()split the function, catch at the call siteparse error
@cImport({ @cInclude("x.h") })translate-c in build.ziginvalid builtin function
std.fmt.allocPrint(gpa, f, v)gpa.print(f, v)*silent* — deprecated shim, compiles today
var gpa: std.heap.DebugAllocator(.{}) = .init;var gpa = std.heap.SafeAllocator.init(backing, .{}); + _ = gpa.deinit()*silent*; deinit() returns a leak count, not .ok
std.heap.stackFallback(1024, backing).get()gone from the shipped stdno member named 'stackFallback'
std.bit_set.IntegerBitSet(8).initEmpty()std.bit_set.Integer(8) = .emptyno member named 'initEmpty'
std.builtin.OptimizeMode.ReleaseSafestd.lang.Optimize.safe*silent* — std.lang does not exist on 0.16
-O ReleaseSafe / -Doptimize=ReleaseSafe-O safe / -Doptimize=safe*silent* aliases on 0.17
@intFromEnum(Mode.on) / @enumFromInt(1)@backingInt(Mode.on) / @fromBackingInt(@intCast(1))*silent*; zig fmt on 0.17 rewrites them for you
inline for (@typeInfo(S).@"struct".fields) |f|inline for (info.field_names, info.field_types) |n, t|no field named 'field_names' the other way — struct-of-arrays
mem.dupeZ(T, slice)mem.dupeSentinel(T, slice, 0)no field or member function named 'dupeZ'
list.getLastOrNull()list.last()*silent* rename
@bitCast(extern_struct_value)@ptrCast(&s)@bitCast rejects extern struct / extern union
b.build_rootb.rootb.root does not exist on 0.16
if (b.args) |args| run.addArgs(args);run.addPassthruArgs()b.args is 0.16-only; passthru takes zero args
b.findProgram(.{ .preferred_program_name = "cc" })b.findProgramLazy(...)0.17-only; the eager call poisons the configure cache
mem.eql(f64, &a, &b) on two NaNs → true→ false*silent* semantics change — same code, different answer
quoting with {f} + std.zig.fmtId{q} / {qf}0.16 has neither specifier
Two things people migrate that do not need migrating:--watch and -fincremental exist on 0.16 too (measured: both run). b.addTranslateC has the same signature on both compilers — the external translate-c package is the stated future direction, not a 0.17 requirement. Version-gating either one is a bug you write yourself.
#119

The Zen of Zig

Six lines that explain most design decisions — and most of the gotchas above.

  • Communicate intent precisely.
  • Edge cases matter.
  • Only one way to do things.
  • No hidden control flow.
  • No hidden allocations.
  • Together, we serve the users.

The design enforces it: allocation is explicit (the Allocator parameter), control flow is visible (errors are values, no exceptions, no operator overloading) — which is exactly why the gotchas in this section exist.

#120

Reading Compiler Errors

Zig errors explain coercions, offer help: hints, and can be produced without emitting a binary.

  • Errors include coercion explanations ("expected type X, found Y") — read top to bottom
  • help: lines usually contain the fix
  • Reference traces show where each mismatched type came from
  • Typecheck only: zig build-exe main.zig -fno-emit-bin
  • Step-level detail for build failures: zig build --summary all
  • error: unused ... → discard with _ = x; (or name it _)
  • "expected type" mismatches → check the casting table (see Quick Reference)
The discard fix
fn f(gpa: std.mem.Allocator) !void {
    const s = try gpa.alloc(u8, 8); // error: unused local variable 's'
    _ = s; // fix: explicit discard
}

Zig's error messages are unusually pedagogical — when the compiler complains, the explanation is usually longer than the fix.

Section 21 of 21: Quick Reference

5 entries

Print-friendly tables: operators, literals, builtins, casts, and where to read more.

#121

Operators & Precedence

All operators, grouped highest to lowest precedence, with the wrap/saturate variants.

precedenceoperatorsmeaning
1 (highest)x.* x.? x[i] x.f f() @b()postfix: deref, unwrap, index, field, call
2! - ~ &xunary: not, negate, bit-not, address-of
3* / % ** *% *|multiply, divide, remainder, power, wrap-mul, sat-mul
4+ - ++ +| +% -| -%add, subtract, concat, sat-add, wrap-add, sat-sub, wrap-sub
5<< >> <<|shift left/right, saturating shift left
6& ^ |bitwise and, xor, or
7== != < > <= >=comparison
8and orlogical, short-circuit
9 (lowest)= += -= *= /= %= *= **= *%= <<= >>= &= |= ^= +|= +%= -|= -%= <<|=assignment (a statement, not an expression)
  • ++ concatenates arrays and slices (comptime-known result for arrays)
  • +% / -% / *% wrap on overflow; +| / -| / *| saturate; <<| saturates the shift
  • and / or short-circuit and require bool operands
  • No operator overloading anywhere — operators always mean bit/math operations
#122

Literal Syntax

Every literal form: integer bases, chars, floats, strings, enum/struct/error literals, ranges.

kindexamples
integers42 0x2A 0o52 0b101010 1_000_000 (separators)
characters'a' '\n' '\x1b' '\u{263A}'
floats3.14 1e9 0x1.8p3 (hex float)
strings"hi\n" "\xAF" (byte) multiline with \\
enum literal.tag
struct / tuple literal.{ .x = 1 } .{ 1, 2 }
errorserror.OutOfMemory error.Set{ .A, .B }
switch ranges'a'...'z' 1...9 (three dots)
anon list → array.{ 1, 2, 3 } coerces to [3]u8 (anonymous list, since 0.15)
Literals in one glance
const hex: u32 = 0xFF_00;
const nl: u8 = '\n';
const f: f64 = 0x1.8p3; // 12.0
const s: []const u8 = "hi\n" ++ "there";
const multi =
    \\line one
    \\line two
;

.{ ... } is the anonymous literal — it becomes a struct (.{ .x = 1 }), a tuple (.{ 1, 2 }), or an array/tuple depending on the target type.

#123

Builtin Functions Index

The @-functions grouped by purpose — introspection, casts, math, SIMD, compile-time, runtime.

groupbuiltins (0.16)
Introspection@typeInfo @typeName @TypeOf @sizeOf @alignOf @bitSizeOf @offsetOf @This @field @hasDecl @hasField @extern
Casts@intCast @truncate @floatCast @floatFromInt @intFromFloat @enumFromInt @intFromEnum @bitCast @ptrCast @alignCast @constCast @volatileCast @addrSpaceCast
Math@min @max @abs @sqrt @sin @cos @tan @exp @log @log2 @log10 @floor @ceil @round @trunc @mod @rem @divTrunc @divFloor @divExact @mulAdd @popCount @clz @ctz @byteSwap @bitReverse
Overflow-aware@addWithOverflow @subWithOverflow @mulWithOverflow @shlWithOverflow
SIMD@splat @reduce @select @shuffle @mulAdd
Compile-time@compileError @compileLog @setEvalBranchQuota @setRuntimeSafety @embedFile @import @src @call @export
Runtime@panic @breakpoint @fence @errorName @errorReturnTrace @returnAddress @frameAddress @prefetch
Pointers@ptrFromInt @intFromPtr
Type creators (0.16)@Int @Float @Array @Pointer @Struct @Union @Enum @Tuple @Opaque @Optional @ErrorUnion @ErrorSet @Fn @EnumLiteral
groupbuiltins (0.17)
Introspection@typeInfo @typeName @TypeOf @sizeOf @alignOf @bitSizeOf @offsetOf @This @field @hasDecl @hasField @extern
Casts@intCast @truncate @floatCast @floatFromInt @intFromFloat @fromBackingInt @backingInt @bitCast @ptrCast @alignCast @constCast @volatileCast @addrSpaceCast
Math@min @max @abs @sqrt @sin @cos @tan @exp @log @log2 @log10 @floor @ceil @round @trunc @mod @rem @divTrunc @divFloor @divExact @divCeil @mulAdd @popCount @clz @ctz @byteSwap @bitReverse
Overflow-aware@addWithOverflow @subWithOverflow @mulWithOverflow @shlWithOverflow
SIMD@splat @reduce @select @shuffle @mulAdd
Compile-time@compileError @compileLog @setEvalBranchQuota @setRuntimeSafety @embedFile @import @src @call @export
Runtime@panic @breakpoint @fence @errorName @errorReturnTrace @returnAddress @frameAddress @prefetch
Pointers@ptrFromInt @intFromPtr
Type creators@Int @Float @Array @Pointer @Struct @Union @Enum @Tuple @Opaque @Optional @ErrorUnion @ErrorSet @Fn @EnumLiteral
new in 0.17what it does
@divCeil(a, b)integer division rounded UP — @divCeil(7, 2) == 4, the missing partner of @divFloor
@backingInt(E.tag)the tag as its backing integer — the 0.17 name for @intFromEnum. @backingInt(Mode.on) is u8 for enum(u8), u2 for a plain enum { red, green, blue }
@fromBackingInt(v)an enum tag from an integer — the 0.17 name for @enumFromInt. ONE argument: the enum type comes from the expected type, so write const m: Mode = @fromBackingInt(@as(u8, 1));

The enum pair was renamed, not removed: @intFromEnum and @enumFromInt still compile on 0.17. They are hidden from the 0.17 Casts row because they are no longer the spelling to write — curation, not a compiler break. zig fmt on 0.17 rewrites them: @intFromEnum(Mode.on) becomes @backingInt(Mode.on) and @enumFromInt(1) becomes @fromBackingInt(@intCast(1)). The other direction IS a compile break: on 0.16 both new names are rejected with invalid builtin function: '@backingInt' / '@fromBackingInt'.

@fromBackingInt takes ONE argument — the value. The enum type is taken from the expected type. @fromBackingInt(Mode, 2) is a 0.17 error: expected 1 argument, found 2. const y = @fromBackingInt(v) with no annotation is also an error: @fromBackingInt must have a known result type, note use @as to provide explicit result type. Annotate the target (const y: Mode = ...) or wrap the value in @as.

0.16 has no rounding-up division: @divCeil is an invalid builtin function there. Switch to the 0.16 tab and the row above disappears.

@Type was removed in 0.16 and replaced by the individual type creators in the last row. Full signatures live in the std docs; every builtin is documented in the language reference.

#124

Casting Cheat Table

Which builtin converts what — and where the safe-mode checks kick in.

from → tobuiltin (0.16)notes
int → smaller int@intCastpanics on truncation in safe modes
int → bigger intcoercion or @intCastimplicit up-cast just works
int → float@floatFromInt—
float → int@intFromFloattruncates; out-of-range is UB
float → smaller float@floatCastmay lose precision
enum → int@intFromEnum—
int → enum@enumFromIntno tag for that value: compile error when the value is comptime-known, invalid enum value panic in safe modes, UB in ReleaseFast
ptr → ptr@ptrCast (+ @alignCast)keep the alignment legal
bits reinterpret@bitCastsource and target must have equal size
[]T → []const Tcoercionimplicit, free
?T → T.?panics on null in safe modes
E!T → Ttry / catcherror handling, not a cast builtin
from → tobuiltin (0.17)notes
int → smaller int@intCastpanics on truncation in safe modes
int → bigger intcoercion or @intCastimplicit up-cast just works
int → float@floatFromInt—
float → int@intFromFloattruncates; out-of-range is UB
float → smaller float@floatCastmay lose precision
enum → int@backingInt0.17 name for @intFromEnum, which still compiles
int → enum@fromBackingIntONE argument — the value; the enum type is the expected type. @fromBackingInt(E, 2) is a compile error. Same tag rules as 0.16: comptime-known bad value is a compile error, runtime bad value panics in safe modes
ptr → ptr@ptrCast (+ @alignCast)keep the alignment legal
bits reinterpret@bitCastsource and target must have equal size
[]T → []const Tcoercionimplicit, free
?T → T.?panics on null in safe modes
E!T → Ttry / catcherror handling, not a cast builtin

The two enum casts were renamed in 0.17: @intFromEnum -> @backingInt, @enumFromInt -> @fromBackingInt. The old pair is deprecated, not deleted — it compiles on 0.17, so the 0.17 tab hides it as curation, not as a compile break. @fromBackingInt takes ONE argument (the value); the enum type comes from the expected type, which is the trap that bites readers coming from @enumFromInt.

Four casts in four lines
const big: u64 = 300;
const small: i32 = @intCast(big); // panics if it doesn't fit (safe modes)
const approx: f64 = @floatFromInt(big);
const bits: u32 = @bitCast(@as(f32, 1.0)); // reinterpret same-size bits

When two types coerce implicitly, no builtin is needed — the "expected type X, found Y" error usually tells you which cast the compiler wants.

#125

Links & Resources

Official docs, std reference, ziglings, community — and where the 0.16 changes are listed.

resourcewhat it is
ziglang.orgdownloads, official docs, blog
ziglang.org/documentation/master/language reference
ziglang.org/documentation/master/std/standard library docs
zig.guidecommunity beginner guide
codeberg.org/ziglings/exercisesziglings — fix small broken programs
ziggit.devcommunity forum
github.com/ziglang/zigsource, issues, PRs
ziglang.org/download/0.17.0/release-notes.html0.17.0 release notes — everything that changed
resourcewhat it is
ziglang.org/download/0.16.0/release-notes.html0.16.0 release notes — everything that changed

This site targets the Zig release named in the header chip; the version tabs are the releases it verifies code against. since badges mark the release each entry's API arrived in. Ziglings exercise numbers appear throughout as cross-references — work through them top to bottom for muscle memory.

Learn by fixing broken programs

Every entry links to related ziglings exercises — tiny broken Zig programs you fix to learn the language.

Start ziglings