Zig Language Reference (v0.16.0)
This skill covers the Zig 0.16.0 language and standard library. Use it when writing, reviewing, or migrating Zig code, working with build.zig / build.zig.zon, standard library modules, and comptime metaprogramming.
Zig evolves rapidly. Training data, blog posts, and many public examples are stale. This skill is the main Zig 0.16.0 aggregate skill for this repository: it condenses the official 0.16.0 language reference, the official std index, the Chinese Zig homepage, and the local offline reference set under references/.
Capability Boundaries
✅ Strong Suits
- Writing and optimizing Zig 0.16.0 code with standard library modules
- Using the build.zig / build.zig.zon build system
- Comptime metaprogramming, builtin functions, and type reflection
- C interop: @cImport, linking, header management
- Code review and migration: older versions → 0.16.0
⚠️ Requirements
- Target version must be confirmed as 0.16.0 (run
zig version)
- Library-specific work (raylib/SDL3) should switch to the dedicated skill
- Platform-specific APIs may require additional OS knowledge
❌ Out of Scope (with alternatives)
- Game/graphics API development → use zig-raylib or zig-sdl3-bindings
- Database/backend service development → use appropriate domain skill
- Non-Zig language coding → use the corresponding language skill
When to use this skill
Use this skill when the user needs to write, review, debug, or migrate Zig 0.16.0 code, or when working with build.zig / build.zig.zon, std modules, comptime, or C interop.
Data Privacy
This skill does not collect, store, or transmit any user data. All code examples are for local development reference only.
Official Positioning
From the Zig 0.16.0 docs and Chinese homepage, Zig is a general-purpose programming language and toolchain for building robust, optimal, and reusable software.
Core design ideas
- No implicit control flow.
- No implicit memory allocation.
- No preprocessor and no macros.
comptime makes type-driven programming and code generation first-class.
- Zig is both a language and a cross-platform toolchain for Zig, C, and C++ projects.
Primary official sources
Quick Start
Example invocations:
Write an HTTP server in Zig 0.16 using std.http
Create a build.zig that depends on a third-party library
Review this Zig code for 0.16 compatibility issues
Migrate this Zig 0.14 project to 0.16
Workflow
Step 1. Confirm version — Run zig version to verify the user is on 0.16.0
Step 2. Review official reference — Read the main skill body for the overall framework
Step 3. Look up std modules — Find the relevant module from the std index, then load the matching references/ file
Step 4. Use examples — Load copyable code snippets from examples/
Step 5. Handle migrations — For legacy code, check the Removed Features and Breaking Changes sections
Critical: How to use this skill
- Confirm the user is targeting Zig 0.16.0 or wants modern Zig patterns.
- Start here for language, build system, std modules, code review, or migration work.
- Prefer local
references/*.md when you need concrete examples or offline guidance.
- Use the official links above for authority, API confirmation, and section names.
- Switch to
zig-raylib or zig-sdl3-bindings only for those library-specific workflows.
Critical: Official 0.16.0 coverage map
The official Zig 0.16.0 language reference covers these major areas:
- Introduction and Zig Standard Library entry.
- Hello World, comments, doc comments, top-level docs, identifiers, values, literals, assignment, and destructuring.
test declarations, doctests, leak reporting, test output, and std.testing.
- Integers, floats, operators, arrays, vectors, pointers, many-item pointers, slices, sentinel-terminated types, and optional pointers.
struct, enum, union, opaque, tuples, anonymous literals, non-exhaustive enums, tagged unions, and result location semantics.
- Blocks, labels,
switch, while, for, if, defer, errdefer, unreachable, and noreturn.
- Functions, methods, errors, optionals, casts, coercions, peer type resolution, and zero-bit types.
comptime, generic data structures, builtin functions, atomics, async-related syntax history, and assembly.
- C interop related builtins such as
@cImport, @cInclude, @extern, and @export.
- The Zig Build System, which points to the dedicated build-system docs.
Critical: Standard library 0.16.0 coverage map
The official 0.16.0 std index exposes the modules most often needed for application work:
- Build and tooling:
std.Build, std.zig, std.zon
- I/O and OS:
std.Io, std.fs, std.process, std.os, std.c
- Memory and text:
std.heap, std.mem, std.fmt, std.ascii, std.unicode, std.base64
- Data and networking:
std.http, std.json, std.Uri, std.net
- Runtime services:
std.log, std.debug, std.testing, std.time, std.Tz
- Algorithms and utilities:
std.math, std.hash, std.crypto, std.Random, std.sort, std.simd
- Concurrency and reflection:
std.Thread, std.atomic, std.meta
- Containers:
std.ArrayList, std.HashMap, std.ArrayHashMap, std.MultiArrayList, std.StaticStringMap, std.bit_set, std.PriorityQueue
Use the official std index to confirm module names and the local references/ folder for curated examples and practical notes.
Critical: Removed Features Still Missing in 0.16
usingnamespace - removed
// WRONG
pub usingnamespace @import("other.zig");
// CORRECT
const other = @import("other.zig");
pub const foo = other.foo;
async/await - removed
These keywords are still not part of normal Zig 0.16 source code patterns. Do not suggest legacy async examples from old posts.
@fence - removed
Use stronger atomic orderings or RMW operations instead.
Critical: I/O API Rewrite
The std.io era patterns remain stale. Modern Zig uses std.Io.Writer and std.Io.Reader with explicit buffers and interface access.
Writing
// WRONG - old API
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello\n", .{});
// CORRECT - modern API
var buf: [4096]u8 = undefined;
var stdout_writer = std.fs.File.stdout().writer(&buf);
const stdout = &stdout_writer.interface;
try stdout.print("Hello\n", .{});
try stdout.flush();
Reading
var buf: [4096]u8 = undefined;
var file_reader = file.reader(&buf);
const r = &file_reader.interface;
while (try r.takeDelimiter('\n')) |line| {
// line does not include '\n'
}
Fixed writer and reader
var out_buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&out_buf);
try w.print("Hello {s}", .{"world"});
const result = w.buffered();
var r: std.Io.Reader = .fixed("hello\nworld");
const first = (try r.takeDelimiter('\n')).?;
_ = first;
Deprecated names such as BufferedWriter, GenericWriter, AnyWriter, and FixedBufferStream should not be suggested for Zig 0.16 code.
Critical: Build System
The official 0.16.0 docs describe the Zig Build System as a cross-platform, dependency-free way to declare project build logic in build.zig.
Core workflow
- Run
zig init or scaffold the project manually.
- Inspect available options with
zig build --help.
- Put package metadata and dependencies in
build.zig.zon.
- Use
std.Build and module-based APIs in build.zig.
Modern build pattern
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);
}
root_module is mandatory
// WRONG - removed field on addExecutable/addLibrary/addTest
b.addExecutable(.{
.name = "app",
.root_source_file = b.path("src/main.zig"),
});
// CORRECT
b.addExecutable(.{
.name = "app",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
}),
});
Module imports changed
// WRONG
exe.addModule("helper", helper_mod);
// CORRECT
exe.root_module.addImport("helper", helper_mod);
Dependency modules
const dep = b.dependency("lib", .{
.target = target,
.optimize = optimize,
});
exe.root_module.addImport("lib", dep.module("lib"));
Compile-level methods like exe.linkSystemLibrary() and exe.addCSourceFiles() should generally move to exe.root_module.* based APIs in modern code.
Critical: Container Initialization
Never suggest .{} for container initialization unless the type is documented to support it. For the common std containers and allocators, Zig 0.16 still expects .empty or .init.
// WRONG
var list: std.ArrayList(u32) = .{};
var gpa: std.heap.DebugAllocator(.{}) = .{};
// CORRECT
var list: std.ArrayList(u32) = .empty;
var map: std.AutoHashMapUnmanaged(u32, u32) = .empty;
var gpa: std.heap.DebugAllocator(.{}) = .init;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
Naming changes that remain relevant
std.ArrayListUnmanaged -> std.ArrayList
std.heap.GeneralPurposeAllocator -> std.heap.DebugAllocator
std.BoundedArray replacement
var buffer: [8]i32 = undefined;
var stack = std.ArrayList(i32).initBuffer(&buffer);
Critical: Format Strings
Some custom formatters now require {f}:
// WRONG
std.debug.print("{}", .{std.zig.fmtId("x")});
// CORRECT
std.debug.print("{f}", .{std.zig.fmtId("x")});
Modern format methods also use writer-based signatures:
pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {
_ = self;
_ = writer;
}
Official Zig 0.16 workflow
Learn and bootstrap
- Read the Introduction section first.
- Use
zig version to confirm the compiler is 0.16.0.
- Use the Chinese homepage positioning when explaining Zig to users: robust, optimal, reusable.
Build, run, test
zig build
zig build run
zig test src/main.zig
zig build test
Chinese homepage sample pattern
const std = @import("std");
const parseInt = std.fmt.parseInt;
test "parse integers" {
const input = "123 67 89,99";
const gpa = std.testing.allocator;
var list: std.ArrayList(u32) = .empty;
defer list.deinit(gpa);
var it = std.mem.tokenizeAny(u8, input, " ,");
while (it.next()) |num| {
const n = try parseInt(u32, num, 10);
try list.append(gpa, n);
}
const expected = [_]u32{ 123, 67, 89, 99 };
for (expected, list.items) |exp, actual| {
try std.testing.expectEqual(exp, actual);
}
}
Breaking Changes Carried Forward from Recent Releases
These patterns are still useful for 0.16 review and migration work:
@branchHint replaces @setCold
// WRONG
@setCold(true);
// CORRECT
@branchHint(.cold);
@export takes a pointer
// WRONG
@export(foo, .{ .name = "bar" });
// CORRECT
@export(&foo, .{ .name = "bar" });
Typed inline asm clobbers
// WRONG
: "rcx", "r11"
// CORRECT
: .{ .rcx = true, .r11 = true }
Decl literals
const S = struct {
x: u32,
const default: S = .{ .x = 0 };
fn init(v: u32) S { return .{ .x = v }; }
};
const a: S = .default;
const b: S = .init(42);
Labeled switch
state: switch (initial) {
.idle => continue :state .running,
.running => if (done) break :state result else continue :state .running,
.error => return error.Failed,
}
Non-exhaustive enum switch
switch (value) {
.a, .b => {},
else => {}, // other named tags
_ => {}, // unnamed integer values
}
Quick Fixes
| Error |
Fix |
no field 'root_source_file' |
Use root_module = b.createModule(.{...}) in addExecutable/addLibrary/addTest |
use of undefined value |
Arithmetic on undefined is illegal; initialize data before use |
type 'f32' cannot represent integer |
Use a float literal such as 123_456_789.0 |
std.io examples don't compile |
Use std.Io writer/reader patterns with explicit buffers |
Old container init example uses .{} |
Prefer .empty or .init depending on the type |
ambiguous format string |
Use {f} for custom formatter output |
sanitize_c = true no longer works |
Use the modern enum-style sanitize configuration from recent Zig releases |
std.fifo.LinearFifo examples fail |
Prefer std.Io.Reader or std.Io.Writer based streaming patterns |
posix.sendfile examples fail |
Use file writer APIs such as .sendFileAll() |
std.fmt.Formatter examples fail |
Use std.fmt.Alt in modern code |
fmtSliceEscapeLower/fmtSliceEscapeUpper missing |
Use std.ascii.hexEscape(bytes, .lower/.upper) |
| User's zig version is not 0.16.0 |
Confirm version, then guide to upgrade or switch skills |
| User asks about raylib/SDL3 API |
Guide to use zig-raylib / zig-sdl3-bindings |
| Code from old blog/tutorial with unknown version |
Use Quick Fixes table to check each compilation error pattern |
| Need module-specific details |
Load the matching local references/*.md file |
| Build-system API uncertainty |
Check both local std-build.md and the official build-system docs |
Offline Examples
Use the local examples/ directory when you need copyable snippets quickly or cannot rely on live web access:
examples/quickstart-workflows.md - starter project, tests, JSON, process, HTTP, review checklist
examples/build-zig-zon-workflows.md - package metadata, dependencies, executable and library layouts
examples/comptime-patterns.md - reflection, generic helpers, generated types, inline loops
examples/c-interop-workflows.md - @cImport, exported APIs, static libraries, headers
examples/std-thread-patterns.md - spawn and join, mutex, wait group, atomic counter patterns
Official Distillations
Use docs/official/ when you need offline distilled versions of the official Zig 0.16 pages themselves rather than topic cards:
docs/official/official-sources.md - source index and navigation
docs/official/official-language-reference-0.16.md - language reference coverage map
docs/official/official-introduction-0.16.md - introduction distillation
docs/official/official-std-index-0.16.md - standard library index distillation
docs/official/official-zh-cn-home-0.16.md - Chinese homepage distillation
Language References
Load these references when working with core language features:
Code Style
- Style Guide - Official Zig naming conventions, whitespace rules, doc comment guidance, redundancy avoidance,
zig fmt
Language Basics & Built-ins
- Language Basics - Core language: types, control flow, error handling, optionals, structs, enums, unions, pointers, slices, comptime, functions
- Built-in Functions - All
@ built-ins: casts, arithmetic, bit ops, memory, atomics, introspection, SIMD, C interop
Standard Library References
Load these references when working with specific modules:
Memory & Slices
- std.mem - Slice search or compare, split or tokenize, alignment, endianness, byte conversion
Text & Encoding
- std.fmt - Format strings, integer or float parsing, custom formatters,
{f} notes
- std.ascii - ASCII classification, case conversion, case-insensitive comparison
- std.unicode - UTF-8 and UTF-16 handling, codepoint iteration, validation
- std.base64 - Base64 encoding and decoding
Math & Random
- std.math - Floating-point ops, trig, checked arithmetic, constants
- std.Random - PRNGs, random integers or floats, shuffle, distributions
- std.hash - Hash functions, checksums, auto-hashing
SIMD & Vectorization
- std.simd - SIMD vector utilities and patterns
Time & Timing
- std.time - Timestamps, timers, epoch conversions, calendar helpers
- std.Tz - Timezone database parsing and timezone handling
Sorting & Searching
- std.sort - Sorting algorithms, binary search, min and max helpers
Core Data Structures
- std.ArrayList - Dynamic arrays and buffer-backed patterns
- std.HashMap / AutoHashMap - Hash maps, string maps, ordered maps
- std.ArrayHashMap - Insertion-order preserving maps
- std.MultiArrayList - Struct-of-arrays storage
- std.SegmentedList - Stable pointers and arena-friendly storage
- std.DoublyLinkedList / SinglyLinkedList - Intrusive linked lists
- std.PriorityQueue - Binary heap based queues
- std.PriorityDequeue - Double-ended priority extraction
- std.Treap - Balanced tree with ordered keys
- std.bit_set - Static and dynamic bit sets
- std.BufMap / BufSet - String-owning maps and sets
- std.StaticStringMap - Compile-time string lookup
- std.enums - EnumSet, EnumMap, EnumArray
Allocators
- std.heap - Allocator selection guide and custom allocator patterns
I/O & Files
- std.Io - Reader and Writer API patterns, buffered I/O, streaming, binary data
- std.fs - Files, directories, iteration, atomic writes, paths
- std.tar - Tar archive handling
- std.zip - ZIP archive handling
- std.compress - Compression and decompression modules
Networking
- std.http - HTTP client or server patterns, TLS, compression
- std.net - Socket basics, address parsing, DNS
- std.Uri - URI parsing, percent-encoding, relative resolution
Process Management
- std.process - Child process spawning, environment, arguments, exec
OS-Specific APIs
- std.os - Platform-specific APIs, syscalls, Windows or WASI access
- std.c - C ABI types and libc bindings
Concurrency
- std.Thread - Thread spawning, mutexes, rw locks, conditions, semaphores
- std.atomic - Atomic operations, orderings, compare-and-swap
Patterns & Best Practices
- Zig Patterns - Practical patterns for writing and reviewing Zig code
- Code Review - Review checklist and stale-pattern detection
Audience
| User Type |
Usage |
| Zig beginners |
Write basic code and learn 0.16 API patterns |
| Migration users |
Migrate from older versions by following the Critical sections |
| Experienced developers |
Deep-dive into std modules via references/ and copy patterns from examples/ |
Customization options:
- Specify output format (full code / snippet / diff)
- Request a specific module focus (e.g., build.zig only or I/O only)
Gotchas
- Always confirm the version first — Verify
zig version is 0.16.0 before giving advice; API differences cause compilation errors
- build.zig requires root_module —
addExecutable/addLibrary no longer accept root_source_file; use root_module = b.createModule(...)
- std.Io pattern is mandatory — Old
std.io patterns (e.g. std.io.getStdOut().writer()) do not compile under 0.16.0
- Container init does not use
.{ } — ArrayList/HashMap must use .empty or .init
- Format strings need
{f} — Custom formatter output requires {f} instead of {}
- Prefer offline references — Use
references/ local files over web search to ensure 0.16.0 consistency
- Do not assume the latest compiler — If the user's version is not 0.16.0, guide them to upgrade or switch skills
FAQ
Q: How does this skill differ from zig-0.15?
A: zig-0.16 is the primary skill covering the latest stable 0.16.0 release. zig-0.15 is retained as a legacy compatibility reference.
Q: What if example code fails to compile?
A: Verify zig version outputs 0.16.0. If the version differs, some APIs may have changed. Use the Quick Fixes table to diagnose.
Q: How do I find a specific std module?
A: Look up the module name in the Standard Library References section, then load the matching references/*.md file.
Q: Can I use this offline?
A: Yes. All references/ and examples/ files are local copies and work without internet access.
Q: Does this skill collect my code?
A: No. This skill is a pure documentation reference and does not collect any user data.
Serialization
- std.json - JSON parsing, serialization, dynamic values, streaming
- std.zon - ZON parsing and serialization for
build.zig.zon and configs
Testing & Debug
- std.testing - Unit test assertions and utilities
- std.debug - Panic, assert, stack traces, hex dump
- std.log - Scoped logging and configurable levels
Metaprogramming
- Comptime Reference - Comptime fundamentals, reflection, generic patterns
- std.meta - Type introspection, field iteration, stringToEnum, generic programming
Compiler Utilities
- std.zig - AST parsing, tokenization, source analysis, linters, formatters, ZON parsing
Security & Cryptography
- std.crypto - Hashing, AEAD, signatures, key exchange, password hashing, secure random
Build System
- std.Build - Build system, modules, dependencies, steps, options, testing, C or C++ integration
Interoperability
- C Interop - Exporting C-compatible APIs, calling conventions, libraries, headers, module maps
1---2name: zig-0-163description: Up-to-date Zig 0.16.0 language and standard library skill. Use when writing, reviewing, debugging, or migrating Zig code, working with build.zig/build.zig.zon, std modules, comptime, C interop, and modern 0.16 APIs.4---56# Zig Language Reference (v0.16.0)78This skill covers the Zig 0.16.0 language and standard library. Use it when writing, reviewing, or migrating Zig code, working with build.zig / build.zig.zon, standard library modules, and comptime metaprogramming.910Zig evolves rapidly. Training data, blog posts, and many public examples are stale. This skill is the main Zig 0.16.0 aggregate skill for this repository: it condenses the official 0.16.0 language reference, the official std index, the Chinese Zig homepage, and the local offline reference set under `references/`.1112## Capability Boundaries1314### ✅ Strong Suits151. Writing and optimizing Zig 0.16.0 code with standard library modules162. Using the build.zig / build.zig.zon build system173. Comptime metaprogramming, builtin functions, and type reflection184. C interop: @cImport, linking, header management195. Code review and migration: older versions → 0.16.02021### ⚠️ Requirements221. Target version must be confirmed as 0.16.0 (run `zig version`)232. Library-specific work (raylib/SDL3) should switch to the dedicated skill243. Platform-specific APIs may require additional OS knowledge2526### ❌ Out of Scope (with alternatives)271. Game/graphics API development → use zig-raylib or zig-sdl3-bindings282. Database/backend service development → use appropriate domain skill293. Non-Zig language coding → use the corresponding language skill3031## When to use this skill3233Use this skill when the user needs to write, review, debug, or migrate Zig 0.16.0 code, or when working with build.zig / build.zig.zon, std modules, comptime, or C interop.3435## Data Privacy3637This skill does not collect, store, or transmit any user data. All code examples are for local development reference only.3839## Official Positioning4041From the Zig 0.16.0 docs and Chinese homepage, Zig is a general-purpose programming language and toolchain for building robust, optimal, and reusable software.4243### Core design ideas44- No implicit control flow.45- No implicit memory allocation.46- No preprocessor and no macros.47- `comptime` makes type-driven programming and code generation first-class.48- Zig is both a language and a cross-platform toolchain for Zig, C, and C++ projects.4950### Primary official sources51- [Language reference](https://ziglang.org/documentation/0.16.0/)52- [Introduction](https://ziglang.org/documentation/0.16.0/#Introduction)53- [Standard library index](https://ziglang.org/documentation/0.16.0/std/)54- [Chinese homepage](https://ziglang.org/zh-CN/)55- [Build system documentation](https://ziglang.org/learn/build-system/)56- [0.16.0 release notes](https://ziglang.org/download/0.16.0/release-notes.html)5758## Quick Start5960**Example invocations:**61```62Write an HTTP server in Zig 0.16 using std.http63Create a build.zig that depends on a third-party library64Review this Zig code for 0.16 compatibility issues65Migrate this Zig 0.14 project to 0.1666```6768## Workflow6970Step 1. **Confirm version** — Run `zig version` to verify the user is on 0.16.07172Step 2. **Review official reference** — Read the main skill body for the overall framework7374Step 3. **Look up std modules** — Find the relevant module from the std index, then load the matching `references/` file7576Step 4. **Use examples** — Load copyable code snippets from `examples/`7778Step 5. **Handle migrations** — For legacy code, check the Removed Features and Breaking Changes sections7980## Critical: How to use this skill81821. Confirm the user is targeting Zig 0.16.0 or wants modern Zig patterns.832. Start here for language, build system, std modules, code review, or migration work.843. Prefer local `references/*.md` when you need concrete examples or offline guidance.854. Use the official links above for authority, API confirmation, and section names.865. Switch to `zig-raylib` or `zig-sdl3-bindings` only for those library-specific workflows.8788## Critical: Official 0.16.0 coverage map8990The official Zig 0.16.0 language reference covers these major areas:9192- Introduction and Zig Standard Library entry.93- Hello World, comments, doc comments, top-level docs, identifiers, values, literals, assignment, and destructuring.94- `test` declarations, doctests, leak reporting, test output, and `std.testing`.95- Integers, floats, operators, arrays, vectors, pointers, many-item pointers, slices, sentinel-terminated types, and optional pointers.96- `struct`, `enum`, `union`, `opaque`, tuples, anonymous literals, non-exhaustive enums, tagged unions, and result location semantics.97- Blocks, labels, `switch`, `while`, `for`, `if`, `defer`, `errdefer`, `unreachable`, and `noreturn`.98- Functions, methods, errors, optionals, casts, coercions, peer type resolution, and zero-bit types.99- `comptime`, generic data structures, builtin functions, atomics, async-related syntax history, and assembly.100- C interop related builtins such as `@cImport`, `@cInclude`, `@extern`, and `@export`.101- The Zig Build System, which points to the dedicated build-system docs.102103## Critical: Standard library 0.16.0 coverage map104105The official 0.16.0 std index exposes the modules most often needed for application work:106107- Build and tooling: `std.Build`, `std.zig`, `std.zon`108- I/O and OS: `std.Io`, `std.fs`, `std.process`, `std.os`, `std.c`109- Memory and text: `std.heap`, `std.mem`, `std.fmt`, `std.ascii`, `std.unicode`, `std.base64`110- Data and networking: `std.http`, `std.json`, `std.Uri`, `std.net`111- Runtime services: `std.log`, `std.debug`, `std.testing`, `std.time`, `std.Tz`112- Algorithms and utilities: `std.math`, `std.hash`, `std.crypto`, `std.Random`, `std.sort`, `std.simd`113- Concurrency and reflection: `std.Thread`, `std.atomic`, `std.meta`114- Containers: `std.ArrayList`, `std.HashMap`, `std.ArrayHashMap`, `std.MultiArrayList`, `std.StaticStringMap`, `std.bit_set`, `std.PriorityQueue`115116Use the official std index to confirm module names and the local `references/` folder for curated examples and practical notes.117118## Critical: Removed Features Still Missing in 0.16119120### `usingnamespace` - removed121```zig122// WRONG123pub usingnamespace @import("other.zig");124125// CORRECT126const other = @import("other.zig");127pub const foo = other.foo;128```129130### `async`/`await` - removed131These keywords are still not part of normal Zig 0.16 source code patterns. Do not suggest legacy async examples from old posts.132133### `@fence` - removed134Use stronger atomic orderings or RMW operations instead.135136## Critical: I/O API Rewrite137138The `std.io` era patterns remain stale. Modern Zig uses `std.Io.Writer` and `std.Io.Reader` with explicit buffers and interface access.139140### Writing141```zig142// WRONG - old API143const stdout = std.io.getStdOut().writer();144try stdout.print("Hello\n", .{});145146// CORRECT - modern API147var buf: [4096]u8 = undefined;148var stdout_writer = std.fs.File.stdout().writer(&buf);149const stdout = &stdout_writer.interface;150try stdout.print("Hello\n", .{});151try stdout.flush();152```153154### Reading155```zig156var buf: [4096]u8 = undefined;157var file_reader = file.reader(&buf);158const r = &file_reader.interface;159160while (try r.takeDelimiter('\n')) |line| {161 // line does not include '\n'162}163```164165### Fixed writer and reader166```zig167var out_buf: [256]u8 = undefined;168var w: std.Io.Writer = .fixed(&out_buf);169try w.print("Hello {s}", .{"world"});170const result = w.buffered();171172var r: std.Io.Reader = .fixed("hello\nworld");173const first = (try r.takeDelimiter('\n')).?;174_ = first;175```176177Deprecated names such as `BufferedWriter`, `GenericWriter`, `AnyWriter`, and `FixedBufferStream` should not be suggested for Zig 0.16 code.178179## Critical: Build System180181The official 0.16.0 docs describe the Zig Build System as a cross-platform, dependency-free way to declare project build logic in `build.zig`.182183### Core workflow184- Run `zig init` or scaffold the project manually.185- Inspect available options with `zig build --help`.186- Put package metadata and dependencies in `build.zig.zon`.187- Use `std.Build` and module-based APIs in `build.zig`.188189### Modern build pattern190```zig191const std = @import("std");192193pub fn build(b: *std.Build) void {194 const target = b.standardTargetOptions(.{});195 const optimize = b.standardOptimizeOption(.{});196197 const exe = b.addExecutable(.{198 .name = "app",199 .root_module = b.createModule(.{200 .root_source_file = b.path("src/main.zig"),201 .target = target,202 .optimize = optimize,203 }),204 });205206 b.installArtifact(exe);207}208```209210### `root_module` is mandatory211```zig212// WRONG - removed field on addExecutable/addLibrary/addTest213b.addExecutable(.{214 .name = "app",215 .root_source_file = b.path("src/main.zig"),216});217218// CORRECT219b.addExecutable(.{220 .name = "app",221 .root_module = b.createModule(.{222 .root_source_file = b.path("src/main.zig"),223 }),224});225```226227### Module imports changed228```zig229// WRONG230exe.addModule("helper", helper_mod);231232// CORRECT233exe.root_module.addImport("helper", helper_mod);234```235236### Dependency modules237```zig238const dep = b.dependency("lib", .{239 .target = target,240 .optimize = optimize,241});242exe.root_module.addImport("lib", dep.module("lib"));243```244245Compile-level methods like `exe.linkSystemLibrary()` and `exe.addCSourceFiles()` should generally move to `exe.root_module.*` based APIs in modern code.246247## Critical: Container Initialization248249Never suggest `.{}` for container initialization unless the type is documented to support it. For the common std containers and allocators, Zig 0.16 still expects `.empty` or `.init`.250251```zig252// WRONG253var list: std.ArrayList(u32) = .{};254var gpa: std.heap.DebugAllocator(.{}) = .{};255256// CORRECT257var list: std.ArrayList(u32) = .empty;258var map: std.AutoHashMapUnmanaged(u32, u32) = .empty;259var gpa: std.heap.DebugAllocator(.{}) = .init;260var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);261```262263### Naming changes that remain relevant264- `std.ArrayListUnmanaged` -> `std.ArrayList`265- `std.heap.GeneralPurposeAllocator` -> `std.heap.DebugAllocator`266267### `std.BoundedArray` replacement268```zig269var buffer: [8]i32 = undefined;270var stack = std.ArrayList(i32).initBuffer(&buffer);271```272273## Critical: Format Strings274275Some custom formatters now require `{f}`:276277```zig278// WRONG279std.debug.print("{}", .{std.zig.fmtId("x")});280281// CORRECT282std.debug.print("{f}", .{std.zig.fmtId("x")});283```284285Modern format methods also use writer-based signatures:286287```zig288pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void {289 _ = self;290 _ = writer;291}292```293294## Official Zig 0.16 workflow295296### Learn and bootstrap297- Read the Introduction section first.298- Use `zig version` to confirm the compiler is `0.16.0`.299- Use the Chinese homepage positioning when explaining Zig to users: robust, optimal, reusable.300301### Build, run, test302```bash303zig build304zig build run305zig test src/main.zig306zig build test307```308309### Chinese homepage sample pattern310```zig311const std = @import("std");312const parseInt = std.fmt.parseInt;313314test "parse integers" {315 const input = "123 67 89,99";316 const gpa = std.testing.allocator;317318 var list: std.ArrayList(u32) = .empty;319 defer list.deinit(gpa);320321 var it = std.mem.tokenizeAny(u8, input, " ,");322 while (it.next()) |num| {323 const n = try parseInt(u32, num, 10);324 try list.append(gpa, n);325 }326327 const expected = [_]u32{ 123, 67, 89, 99 };328 for (expected, list.items) |exp, actual| {329 try std.testing.expectEqual(exp, actual);330 }331}332```333334## Breaking Changes Carried Forward from Recent Releases335336These patterns are still useful for 0.16 review and migration work:337338### `@branchHint` replaces `@setCold`339```zig340// WRONG341@setCold(true);342343// CORRECT344@branchHint(.cold);345```346347### `@export` takes a pointer348```zig349// WRONG350@export(foo, .{ .name = "bar" });351352// CORRECT353@export(&foo, .{ .name = "bar" });354```355356### Typed inline asm clobbers357```zig358// WRONG359: "rcx", "r11"360361// CORRECT362: .{ .rcx = true, .r11 = true }363```364365### Decl literals366```zig367const S = struct {368 x: u32,369 const default: S = .{ .x = 0 };370 fn init(v: u32) S { return .{ .x = v }; }371};372373const a: S = .default;374const b: S = .init(42);375```376377### Labeled switch378```zig379state: switch (initial) {380 .idle => continue :state .running,381 .running => if (done) break :state result else continue :state .running,382 .error => return error.Failed,383}384```385386### Non-exhaustive enum switch387```zig388switch (value) {389 .a, .b => {},390 else => {}, // other named tags391 _ => {}, // unnamed integer values392}393```394395## Quick Fixes396397| Error | Fix |398|-------|-----|399| `no field 'root_source_file'` | Use `root_module = b.createModule(.{...})` in `addExecutable`/`addLibrary`/`addTest` |400| `use of undefined value` | Arithmetic on `undefined` is illegal; initialize data before use |401| `type 'f32' cannot represent integer` | Use a float literal such as `123_456_789.0` |402| `std.io` examples don't compile | Use `std.Io` writer/reader patterns with explicit buffers |403| Old container init example uses `.{}` | Prefer `.empty` or `.init` depending on the type |404| `ambiguous format string` | Use `{f}` for custom formatter output |405| `sanitize_c = true` no longer works | Use the modern enum-style sanitize configuration from recent Zig releases |406| `std.fifo.LinearFifo` examples fail | Prefer `std.Io.Reader` or `std.Io.Writer` based streaming patterns |407| `posix.sendfile` examples fail | Use file writer APIs such as `.sendFileAll()` |408| `std.fmt.Formatter` examples fail | Use `std.fmt.Alt` in modern code |409| `fmtSliceEscapeLower`/`fmtSliceEscapeUpper` missing | Use `std.ascii.hexEscape(bytes, .lower/.upper)` |410| User's zig version is not 0.16.0 | Confirm version, then guide to upgrade or switch skills |411| User asks about raylib/SDL3 API | Guide to use zig-raylib / zig-sdl3-bindings |412| Code from old blog/tutorial with unknown version | Use Quick Fixes table to check each compilation error pattern |413| Need module-specific details | Load the matching local `references/*.md` file |414| Build-system API uncertainty | Check both local `std-build.md` and the official build-system docs |415416## Offline Examples417418Use the local `examples/` directory when you need copyable snippets quickly or cannot rely on live web access:419420- `examples/quickstart-workflows.md` - starter project, tests, JSON, process, HTTP, review checklist421- `examples/build-zig-zon-workflows.md` - package metadata, dependencies, executable and library layouts422- `examples/comptime-patterns.md` - reflection, generic helpers, generated types, inline loops423- `examples/c-interop-workflows.md` - `@cImport`, exported APIs, static libraries, headers424- `examples/std-thread-patterns.md` - spawn and join, mutex, wait group, atomic counter patterns425426## Official Distillations427428Use `docs/official/` when you need offline distilled versions of the official Zig 0.16 pages themselves rather than topic cards:429430- `docs/official/official-sources.md` - source index and navigation431- `docs/official/official-language-reference-0.16.md` - language reference coverage map432- `docs/official/official-introduction-0.16.md` - introduction distillation433- `docs/official/official-std-index-0.16.md` - standard library index distillation434- `docs/official/official-zh-cn-home-0.16.md` - Chinese homepage distillation435436## Language References437438Load these references when working with core language features:439440### Code Style441- **[Style Guide](references/style-guide.md)** - Official Zig naming conventions, whitespace rules, doc comment guidance, redundancy avoidance, `zig fmt`442443### Language Basics & Built-ins444- **[Language Basics](references/language.md)** - Core language: types, control flow, error handling, optionals, structs, enums, unions, pointers, slices, comptime, functions445- **[Built-in Functions](references/builtins.md)** - All `@` built-ins: casts, arithmetic, bit ops, memory, atomics, introspection, SIMD, C interop446447## Standard Library References448449Load these references when working with specific modules:450451### Memory & Slices452- **[std.mem](references/std-mem.md)** - Slice search or compare, split or tokenize, alignment, endianness, byte conversion453454### Text & Encoding455- **[std.fmt](references/std-fmt.md)** - Format strings, integer or float parsing, custom formatters, `{f}` notes456- **[std.ascii](references/std-ascii.md)** - ASCII classification, case conversion, case-insensitive comparison457- **[std.unicode](references/std-unicode.md)** - UTF-8 and UTF-16 handling, codepoint iteration, validation458- **[std.base64](references/std-base64.md)** - Base64 encoding and decoding459460### Math & Random461- **[std.math](references/std-math.md)** - Floating-point ops, trig, checked arithmetic, constants462- **[std.Random](references/std-random.md)** - PRNGs, random integers or floats, shuffle, distributions463- **[std.hash](references/std-hash.md)** - Hash functions, checksums, auto-hashing464465### SIMD & Vectorization466- **[std.simd](references/std-simd.md)** - SIMD vector utilities and patterns467468### Time & Timing469- **[std.time](references/std-time.md)** - Timestamps, timers, epoch conversions, calendar helpers470- **[std.Tz](references/std-tz.md)** - Timezone database parsing and timezone handling471472### Sorting & Searching473- **[std.sort](references/std-sort.md)** - Sorting algorithms, binary search, min and max helpers474475### Core Data Structures476- **[std.ArrayList](references/std-arraylist.md)** - Dynamic arrays and buffer-backed patterns477- **[std.HashMap / AutoHashMap](references/std-hashmap.md)** - Hash maps, string maps, ordered maps478- **[std.ArrayHashMap](references/std-array-hash-map.md)** - Insertion-order preserving maps479- **[std.MultiArrayList](references/std-multi-array-list.md)** - Struct-of-arrays storage480- **[std.SegmentedList](references/std-segmented-list.md)** - Stable pointers and arena-friendly storage481- **[std.DoublyLinkedList / SinglyLinkedList](references/std-linked-list.md)** - Intrusive linked lists482- **[std.PriorityQueue](references/std-priority-queue.md)** - Binary heap based queues483- **[std.PriorityDequeue](references/std-priority-dequeue.md)** - Double-ended priority extraction484- **[std.Treap](references/std-treap.md)** - Balanced tree with ordered keys485- **[std.bit_set](references/std-bit-set.md)** - Static and dynamic bit sets486- **[std.BufMap / BufSet](references/std-buf-map.md)** - String-owning maps and sets487- **[std.StaticStringMap](references/std-static-string-map.md)** - Compile-time string lookup488- **[std.enums](references/std-enums.md)** - EnumSet, EnumMap, EnumArray489490### Allocators491- **[std.heap](references/std-allocators.md)** - Allocator selection guide and custom allocator patterns492493### I/O & Files494- **[std.Io](references/std-io.md)** - Reader and Writer API patterns, buffered I/O, streaming, binary data495- **[std.fs](references/std-fs.md)** - Files, directories, iteration, atomic writes, paths496- **[std.tar](references/std-tar.md)** - Tar archive handling497- **[std.zip](references/std-zip.md)** - ZIP archive handling498- **[std.compress](references/std-compress.md)** - Compression and decompression modules499500### Networking501- **[std.http](references/std-http.md)** - HTTP client or server patterns, TLS, compression502- **[std.net](references/std-net.md)** - Socket basics, address parsing, DNS503- **[std.Uri](references/std-uri.md)** - URI parsing, percent-encoding, relative resolution504505### Process Management506- **[std.process](references/std-process.md)** - Child process spawning, environment, arguments, exec507508### OS-Specific APIs509- **[std.os](references/std-os.md)** - Platform-specific APIs, syscalls, Windows or WASI access510- **[std.c](references/std-c.md)** - C ABI types and libc bindings511512### Concurrency513- **[std.Thread](references/std-thread.md)** - Thread spawning, mutexes, rw locks, conditions, semaphores514- **[std.atomic](references/std-atomic.md)** - Atomic operations, orderings, compare-and-swap515516### Patterns & Best Practices517- **[Zig Patterns](references/patterns.md)** - Practical patterns for writing and reviewing Zig code518- **[Code Review](references/code-review.md)** - Review checklist and stale-pattern detection519520## Audience521522| User Type | Usage |523|-----------|-------|524| **Zig beginners** | Write basic code and learn 0.16 API patterns |525| **Migration users** | Migrate from older versions by following the Critical sections |526| **Experienced developers** | Deep-dive into std modules via references/ and copy patterns from examples/ |527528Customization options:529- Specify output format (full code / snippet / diff)530- Request a specific module focus (e.g., build.zig only or I/O only)531532## Gotchas5335341. **Always confirm the version first** — Verify `zig version` is 0.16.0 before giving advice; API differences cause compilation errors5352. **build.zig requires root_module** — `addExecutable`/`addLibrary` no longer accept `root_source_file`; use `root_module = b.createModule(...)`5363. **std.Io pattern is mandatory** — Old `std.io` patterns (e.g. `std.io.getStdOut().writer()`) do not compile under 0.16.05374. **Container init does not use `.{ }`** — ArrayList/HashMap must use `.empty` or `.init`5385. **Format strings need `{f}`** — Custom formatter output requires `{f}` instead of `{}`5396. **Prefer offline references** — Use `references/` local files over web search to ensure 0.16.0 consistency5407. **Do not assume the latest compiler** — If the user's version is not 0.16.0, guide them to upgrade or switch skills541542## FAQ543544**Q: How does this skill differ from `zig-0.15`?**545A: `zig-0.16` is the primary skill covering the latest stable 0.16.0 release. `zig-0.15` is retained as a legacy compatibility reference.546547**Q: What if example code fails to compile?**548A: Verify `zig version` outputs 0.16.0. If the version differs, some APIs may have changed. Use the Quick Fixes table to diagnose.549550**Q: How do I find a specific std module?**551A: Look up the module name in the Standard Library References section, then load the matching `references/*.md` file.552553**Q: Can I use this offline?**554A: Yes. All references/ and examples/ files are local copies and work without internet access.555556**Q: Does this skill collect my code?**557A: No. This skill is a pure documentation reference and does not collect any user data.558559### Serialization560- **[std.json](references/std-json.md)** - JSON parsing, serialization, dynamic values, streaming561- **[std.zon](references/std-zon.md)** - ZON parsing and serialization for `build.zig.zon` and configs562563### Testing & Debug564- **[std.testing](references/std-testing.md)** - Unit test assertions and utilities565- **[std.debug](references/std-debug.md)** - Panic, assert, stack traces, hex dump566- **[std.log](references/std-log.md)** - Scoped logging and configurable levels567568### Metaprogramming569- **[Comptime Reference](references/comptime.md)** - Comptime fundamentals, reflection, generic patterns570- **[std.meta](references/std-meta.md)** - Type introspection, field iteration, stringToEnum, generic programming571572### Compiler Utilities573- **[std.zig](references/std-zig.md)** - AST parsing, tokenization, source analysis, linters, formatters, ZON parsing574575### Security & Cryptography576- **[std.crypto](references/std-crypto.md)** - Hashing, AEAD, signatures, key exchange, password hashing, secure random577578### Build System579- **[std.Build](references/std-build.md)** - Build system, modules, dependencies, steps, options, testing, C or C++ integration580581### Interoperability582- **[C Interop](references/c-interop.md)** - Exporting C-compatible APIs, calling conventions, libraries, headers, module maps