Zig Language Reference (v0.15)
This skill covers Zig 0.15.x language and standard library. It is retained as a compatibility reference alongside the primary zig-0.16 skill.
Capability Boundaries
✅ Strong Suits
- Writing and reviewing Zig 0.15.x code
- Understanding breaking changes from 0.14 to 0.15
- Using the build.zig / build.zig.zon build system (legacy)
- Comptime metaprogramming and builtin functions
⚠️ Requirements
- Target version must be 0.15.x
- For new projects, prefer zig-0.16 (0.16.0 is the latest stable)
❌ Out of Scope (with alternatives)
- Do not use this for Zig 0.16.0 development → use zig-0.16 skill instead
- Do not use this for game/graphics development → use zig-raylib or zig-sdl3-bindings
When to use
Use this skill when the user confirms they are targeting Zig 0.15.x and need to write or review legacy code.
Data Privacy
This skill does not collect, store, or transmit any user data. All code examples are for local development reference only.
Quick Start
Example invocations:
Write a program in Zig 0.15, scaffold the project
Check if this build.zig compiles under 0.15
Review this code for 0.14→0.15 compatibility issues
Workflow
Step 1. Confirm version — Ask the user to run zig version to confirm 0.15.x
Step 2. Check breaking changes — Review the Removed Features section for deprecated APIs
Step 3. Check I/O patterns — Use the correct std.Io pattern instead of legacy std.io
Step 4. Check build system — Use root_module-based build.zig API
Step 5. Container init — Use .empty/.init instead of .{ }
Step 6. Output code — Provide complete compilable examples
Critical: Removed Features (0.15.x)
usingnamespace - REMOVED
// WRONG - compile error
pub usingnamespace @import("other.zig");
// CORRECT - explicit re-export
const other = @import("other.zig");
pub const foo = other.foo;
async/await - REMOVED
Keywords removed from language. Async I/O support is planned for future releases.
Critical: I/O API Rewrite ("Writergate")
The entire std.io API changed. New std.Io.Writer and std.Io.Reader are non-generic with buffer in the interface.
Writing
// WRONG - old API
const stdout = std.io.getStdOut().writer();
try stdout.print("Hello\n", .{});
// CORRECT - new API: provide buffer, access .interface, flush
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(); // REQUIRED!
Reading
// Reading from file
var buf: [4096]u8 = undefined;
var file_reader = file.reader(&buf);
const r = &file_reader.interface;
// Read line by line (takeDelimiter returns null at EOF)
while (try r.takeDelimiter('\n')) |line| {
// process line (doesn't include '\n')
}
// Read binary data
const header = try r.takeStruct(Header, .little);
const value = try r.takeInt(u32, .big);
Fixed Buffer Writer (no file)
var buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try w.print("Hello {s}", .{"world"});
const result = w.buffered(); // "Hello world"
Fixed Reader (from slice)
var r: std.Io.Reader = .fixed("hello\nworld");
const line = (try r.takeDelimiter('\n')).?; // "hello" (returns null at EOF)
Deprecated: BufferedWriter, CountingWriter, std.io.bufferedWriter()
Deprecated: GenericWriter, GenericReader, AnyWriter, AnyReader, FixedBufferStream
New: std.Io.Writer, std.Io.Reader - non-generic, buffer in interface
Replacements:
CountingWriter → std.Io.Writer.Discarding (has .fullCount())
BufferedWriter → buffer provided to .writer(&buf) call
- Allocating output →
std.Io.Writer.Allocating
Critical: Build System (0.15.x)
root_source_file is REMOVED from addExecutable/addLibrary/addTest. Use root_module:
// WRONG - removed field
b.addExecutable(.{
.name = "app",
.root_source_file = b.path("src/main.zig"), // ERROR
.target = target,
});
// CORRECT
b.addExecutable(.{
.name = "app",
.root_module = b.createModule(.{
.root_source_file = b.path("src/main.zig"),
.target = target,
.optimize = optimize,
}),
});
Module imports changed:
// WRONG (old API)
exe.addModule("helper", helper_mod);
// CORRECT
exe.root_module.addImport("helper", helper_mod);
Adding dependency modules:
const dep = b.dependency("lib", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("lib", dep.module("lib"));
Compile-level methods deprecated: exe.linkSystemLibrary(), exe.addCSourceFiles(),
exe.addIncludePath(), exe.linkLibC() are deprecated — use exe.root_module.* equivalents instead.
See std.Build reference for complete build system documentation.
Critical: Container Initialization
Never use .{} for containers. Use .empty or .init:
// WRONG - deprecated
var list: std.ArrayList(u32) = .{};
var gpa: std.heap.DebugAllocator(.{}) = .{};
// CORRECT - use .empty for empty collections
var list: std.ArrayList(u32) = .empty;
var map: std.AutoHashMapUnmanaged(u32, u32) = .empty;
// CORRECT - use .init for stateful types with internal config
var gpa: std.heap.DebugAllocator(.{}) = .init;
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
Naming Changes
std.ArrayListUnmanaged → std.ArrayList (Unmanaged is now default, old name deprecated)
std.heap.GeneralPurposeAllocator → std.heap.DebugAllocator (GPA alias still works)
std.BoundedArray - REMOVED. Use:
var buffer: [8]i32 = undefined;
var stack = std.ArrayList(i32).initBuffer(&buffer);
Critical: Format Strings (0.15.x)
{f} required to call format methods:
// WRONG - ambiguous error
std.debug.print("{}", .{std.zig.fmtId("x")});
// CORRECT
std.debug.print("{f}", .{std.zig.fmtId("x")});
Format method signature changed:
// OLD - wrong
pub fn format(self: @This(), comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void
// NEW - correct
pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void
Breaking Changes (0.14.0+)
@branchHint replaces @setCold
// WRONG
@setCold(true);
// CORRECT
@branchHint(.cold); // Must be first statement in block
@export takes pointer
// WRONG
@export(foo, .{ .name = "bar" });
// CORRECT
@export(&foo, .{ .name = "bar" });
Inline asm clobbers are typed
// WRONG
: "rcx", "r11"
// CORRECT
: .{ .rcx = true, .r11 = true }
@fence - REMOVED
Use stronger atomic orderings or RMW operations instead.
Decl Literals (0.14.0+)
.identifier syntax works for declarations:
const S = struct {
x: u32,
const default: S = .{ .x = 0 };
fn init(v: u32) S { return .{ .x = v }; }
};
const a: S = .default; // S.default
const b: S = .init(42); // S.init(42)
const c: S = try .init(1); // works with try
Labeled Switch (0.14.0+)
State machines use continue :label:
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 (0.15.x)
Can mix explicit tags with _ and else:
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(.{...}) |
use of undefined value |
Arithmetic on undefined is now illegal |
type 'f32' cannot represent integer |
Use float literal: 123_456_789.0 not 123_456_789 |
ambiguous format string |
Use {f} for format methods |
sanitize_c = true |
Type changed to ?std.zig.SanitizeC — use .full, .trap, or .off |
std.fifo.LinearFifo |
Removed — use std.Io.Reader/Writer patterns |
posix.sendfile |
Removed — use std.fs.File writer .sendFileAll() |
std.fmt.Formatter |
Deprecated — renamed to std.fmt.Alt |
fmtSliceEscapeLower/Upper |
Use std.ascii.hexEscape(bytes, .lower/.upper) |
Language References
Load these references when working with core language features:
Code Style
- Style Guide - Official Zig naming conventions (TitleCase types, camelCase functions, snake_case variables), whitespace rules, doc comment guidance, redundancy avoidance,
zig fmt
Language Basics & Built-ins
- Language Basics - Core language: types, control flow (if/while/for/switch), error handling (try/catch/errdefer), optionals, structs, enums, unions, pointers, slices, comptime, functions
- Built-in Functions - All
@ built-ins: type casts (@intCast, @bitCast, @ptrCast), arithmetic (@addWithOverflow, @divExact), bit ops (@clz, @popCount), memory (@memcpy, @sizeOf), atomics (@atomicRmw, @cmpxchgWeak), introspection (@typeInfo, @TypeOf, @hasDecl), SIMD (@Vector, @splat, @reduce), C interop (@cImport, @export)
Standard Library References
Load these references when working with specific modules:
Memory & Slices
- std.mem - Slice search/compare, split/tokenize, alignment, endianness, byte conversion
Text & Encoding
- std.fmt - Format strings, integer/float parsing, hex encoding, custom formatters,
{f} specifier (0.15.x)
- std.ascii - ASCII character classification (isAlpha, isDigit), case conversion, case-insensitive comparison
- std.unicode - UTF-8/UTF-16 encoding/decoding, codepoint iteration, validation, WTF-8 for Windows
- std.base64 - Base64 encoding/decoding (standard, URL-safe, with/without padding)
Math & Random
- std.math - Floating-point ops, trig, overflow-checked arithmetic, constants, complex numbers, big integers
- std.Random - PRNGs (Xoshiro256, Pcg), CSPRNGs (ChaCha), random integers/floats/booleans, shuffle, distributions
- std.hash - Non-cryptographic hash functions (Wyhash, XxHash, FNV, Murmur, CityHash), checksums (CRC32, Adler32), auto-hashing
SIMD & Vectorization
- std.simd - SIMD vector utilities: optimal vector length, iota/repeat/join/interlace patterns, element shifting/rotation, parallel searching, prefix scans, branchless selection
Time & Timing
- std.time - Wall-clock timestamps, monotonic Instant/Timer, epoch conversions, calendar utilities (year/month/day), time unit constants
- std.Tz - TZif timezone database parsing (RFC 8536), UTC offsets, DST rules, timezone abbreviations, leap seconds
Sorting & Searching
- std.sort - Sorting algorithms (pdq, block, heap, insertion), binary search, min/max
Core Data Structures
- std.ArrayList - Dynamic arrays, vectors, BoundedArray replacement
- std.HashMap / AutoHashMap - Hash maps, string maps, ordered maps
- std.ArrayHashMap - Insertion-order preserving hash map, array-style key/value access
- std.MultiArrayList - Struct-of-arrays for cache-efficient struct storage
- std.SegmentedList - Stable pointers, arena-friendly, non-copyable types
- std.DoublyLinkedList / SinglyLinkedList - Intrusive linked lists, O(1) insert/remove
- std.PriorityQueue - Binary heap, min/max extraction, task scheduling
- std.PriorityDequeue - Min-max heap, double-ended priority extraction
- std.Treap - Self-balancing BST, ordered keys, min/max/predecessor
- std.bit_set - Bit sets (Static, Dynamic, Integer, Array), set operations, iteration
- std.BufMap / BufSet - String-owning maps and sets, automatic key/value memory management
- std.StaticStringMap - Compile-time optimized string lookup, perfect hash for keywords
- std.enums - EnumSet, EnumMap, EnumArray: bit-backed enum collections
Allocators
- std.heap - Allocator selection guide, ArenaAllocator, DebugAllocator, FixedBufferAllocator, MemoryPool, SmpAllocator, ThreadSafeAllocator, StackFallbackAllocator, custom allocator implementation
I/O & Files
- std.io - Reader/Writer API (0.15.x): buffered I/O, streaming, binary data, format strings
- std.fs - File system: files, directories, iteration, atomic writes, paths
- std.tar - Tar archive reading/writing, extraction, POSIX ustar, GNU/pax extensions
- std.zip - ZIP archive reading/extraction, ZIP64 support, store/deflate compression
- std.compress - Compression: DEFLATE (gzip, zlib), Zstandard, LZMA, LZMA2, XZ decompression/compression
Networking
- std.http - HTTP client/server, TLS, connection pooling, compression, WebSocket
- std.net - TCP/UDP sockets, address parsing, DNS resolution
- std.Uri - URI parsing/formatting (RFC 3986), percent-encoding/decoding, relative URI resolution
Process Management
- std.process - Child process spawning, environment variables, argument parsing, exec
OS-Specific APIs
- std.os - OS-specific APIs: Linux syscalls, io_uring, Windows NT APIs, WASI, direct platform access
- std.c - C ABI types and libc bindings: platform-specific types (fd_t, pid_t, timespec), errno values, socket/signal/memory types, fcntl/open flags, FFI with C libraries
Concurrency
- std.Thread - Thread spawning, Mutex, RwLock, Condition, Semaphore, WaitGroup, thread pools
- std.atomic - Lock-free atomic operations: Value wrapper, fetch-and-modify (add/sub/and/or/xor), compare-and-swap, atomic ordering semantics, spin loop hints, cache line sizing
Patterns & Best Practices
- Zig Patterns - Load when writing new code or reviewing code quality. Comprehensive best practices extracted from the Zig standard library: quick patterns (memory/allocators, file I/O, HTTP, JSON, testing, build system) plus idiomatic code patterns covering syntax (closures, context pattern, options structs, destructuring), polymorphism (duck typing, generics, custom formatting, dynamic/static dispatch), safety (diagnostics, error payloads, defer/errdefer, compile-time assertions), and performance (const pointer passing)
- Code Review - Load when reviewing Zig code. Systematic checklist organized by confidence level: ALWAYS FLAG (removed features, changed syntax, API changes), FLAG WITH CONTEXT (exception safety bugs, missing flush, allocator issues), SUGGEST (style improvements). Includes migration examples for 0.14/0.15 breaking changes
Serialization
- std.json - JSON parsing, serialization, dynamic values, streaming, custom parse/stringify
- std.zon - ZON (Zig Object Notation) parsing and serialization for build.zig.zon, config files, data interchange
Testing & Debug
- std.testing - Unit test assertions and utilities
- std.debug - Panic, assert, stack traces, hex dump, format specifiers
- std.log - Scoped logging with configurable levels and output
Metaprogramming
- Comptime Reference - Comptime fundamentals, type reflection (
@typeInfo/@Type/@TypeOf), loop variants (comptime for vs inline for), branch elimination, type generation, comptime limitations
- 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 (SHA2, SHA3, Blake3), AEAD (AES-GCM, ChaCha20-Poly1305), signatures (Ed25519, ECDSA), key exchange (X25519), password hashing (Argon2, scrypt, bcrypt), secure random, timing-safe operations
Build System
- std.Build - Build system: build.zig, modules, dependencies, build.zig.zon, steps, options, testing, C/C++ integration
Interoperability
- C Interop - Exporting C-compatible APIs:
export fn, C calling convention, building static/dynamic libraries, creating headers, macOS universal binaries, XCFramework for Swift/Xcode, module maps
Audience
| User Type |
Usage |
| Zig 0.15 users |
Maintain legacy projects, understand 0.14→0.15 changes |
| Migration users |
Replace deprecated APIs by following the Critical sections |
| Compatibility checkers |
Verify existing code works under 0.15 |
Customization: specify output format (full code / diff / snippet).
Gotchas
- Always confirm the version first — User code may come from any older version; run
zig version to check
- build.zig API differences — 0.15.x
addExecutable uses root_module instead of the old root_source_file
- std.Io pattern — 0.15 partially adopts the new
std.Io pattern; old std.io is incompatible
- Container initialization —
.{ } for ArrayList etc. will error; use .empty or .init
- Format strings — Custom formatters require
{f} instead of {}
- Removed features —
async/await, usingnamespace, @fence are fully removed
FAQ
Q: Should I use zig-0.15 or zig-0.16?
A: For new projects, prefer zig-0.16. zig-0.15 is retained for compatibility with existing 0.15 projects.
Q: What is the biggest difference between 0.15 and 0.14?
A: The I/O API rewrite (std.io → std.Io) and the introduction of root_module in build.zig.
Q: How do I create an executable in 0.15?
A: Use b.addExecutable(.{ .name = "...", .root_module = b.createModule(...) }).
1---2name: zig-0-153description: Up-to-date Zig programming language patterns for version 0.15.x. Use when writing, reviewing, or debugging Zig code, working with build.zig and build.zig.zon files, or using comptime metaprogramming. Critical for avoiding outdated patterns from training data - especially build system APIs (root_module instead of root_source_file), I/O APIs (buffered writer pattern), container initialization (.empty/.init), allocator selection (DebugAllocator), and removed language features (async/await, usingnamespace).4---56# Zig Language Reference (v0.15)78This skill covers Zig 0.15.x language and standard library. It is retained as a compatibility reference alongside the primary zig-0.16 skill.910## Capability Boundaries1112### ✅ Strong Suits131. Writing and reviewing Zig 0.15.x code142. Understanding breaking changes from 0.14 to 0.15153. Using the build.zig / build.zig.zon build system (legacy)164. Comptime metaprogramming and builtin functions1718### ⚠️ Requirements191. Target version must be 0.15.x202. For new projects, prefer zig-0.16 (0.16.0 is the latest stable)2122### ❌ Out of Scope (with alternatives)231. Do not use this for Zig 0.16.0 development → use zig-0.16 skill instead242. Do not use this for game/graphics development → use zig-raylib or zig-sdl3-bindings2526## When to use2728Use this skill when the user confirms they are targeting Zig 0.15.x and need to write or review legacy code.2930## Data Privacy3132This skill does not collect, store, or transmit any user data. All code examples are for local development reference only.3334## Quick Start3536**Example invocations:**37```38Write a program in Zig 0.15, scaffold the project39Check if this build.zig compiles under 0.1540Review this code for 0.14→0.15 compatibility issues41```4243## Workflow4445Step 1. **Confirm version** — Ask the user to run `zig version` to confirm 0.15.x46Step 2. **Check breaking changes** — Review the Removed Features section for deprecated APIs47Step 3. **Check I/O patterns** — Use the correct `std.Io` pattern instead of legacy `std.io`48Step 4. **Check build system** — Use `root_module`-based build.zig API49Step 5. **Container init** — Use `.empty`/`.init` instead of `.{ }`50Step 6. **Output code** — Provide complete compilable examples5152## Critical: Removed Features (0.15.x)5354### `usingnamespace` - REMOVED55```zig56// WRONG - compile error57pub usingnamespace @import("other.zig");5859// CORRECT - explicit re-export60const other = @import("other.zig");61pub const foo = other.foo;62```6364### `async`/`await` - REMOVED65Keywords removed from language. Async I/O support is planned for future releases.6667## Critical: I/O API Rewrite ("Writergate")6869The entire `std.io` API changed. New `std.Io.Writer` and `std.Io.Reader` are **non-generic** with buffer in the interface.7071### Writing72```zig73// WRONG - old API74const stdout = std.io.getStdOut().writer();75try stdout.print("Hello\n", .{});7677// CORRECT - new API: provide buffer, access .interface, flush78var buf: [4096]u8 = undefined;79var stdout_writer = std.fs.File.stdout().writer(&buf);80const stdout = &stdout_writer.interface;81try stdout.print("Hello\n", .{});82try stdout.flush(); // REQUIRED!83```8485### Reading86```zig87// Reading from file88var buf: [4096]u8 = undefined;89var file_reader = file.reader(&buf);90const r = &file_reader.interface;9192// Read line by line (takeDelimiter returns null at EOF)93while (try r.takeDelimiter('\n')) |line| {94 // process line (doesn't include '\n')95}9697// Read binary data98const header = try r.takeStruct(Header, .little);99const value = try r.takeInt(u32, .big);100```101102### Fixed Buffer Writer (no file)103```zig104var buf: [256]u8 = undefined;105var w: std.Io.Writer = .fixed(&buf);106try w.print("Hello {s}", .{"world"});107const result = w.buffered(); // "Hello world"108```109110### Fixed Reader (from slice)111```zig112var r: std.Io.Reader = .fixed("hello\nworld");113const line = (try r.takeDelimiter('\n')).?; // "hello" (returns null at EOF)114```115116**Deprecated:** `BufferedWriter`, `CountingWriter`, `std.io.bufferedWriter()`117118**Deprecated:** `GenericWriter`, `GenericReader`, `AnyWriter`, `AnyReader`, `FixedBufferStream`119120**New:** `std.Io.Writer`, `std.Io.Reader` - non-generic, buffer in interface121122**Replacements:**123- `CountingWriter` → `std.Io.Writer.Discarding` (has `.fullCount()`)124- `BufferedWriter` → buffer provided to `.writer(&buf)` call125- Allocating output → `std.Io.Writer.Allocating`126127## Critical: Build System (0.15.x)128129`root_source_file` is REMOVED from `addExecutable`/`addLibrary`/`addTest`. Use `root_module`:130131```zig132// WRONG - removed field133b.addExecutable(.{134 .name = "app",135 .root_source_file = b.path("src/main.zig"), // ERROR136 .target = target,137});138139// CORRECT140b.addExecutable(.{141 .name = "app",142 .root_module = b.createModule(.{143 .root_source_file = b.path("src/main.zig"),144 .target = target,145 .optimize = optimize,146 }),147});148```149150**Module imports changed:**151```zig152// WRONG (old API)153exe.addModule("helper", helper_mod);154155// CORRECT156exe.root_module.addImport("helper", helper_mod);157```158159**Adding dependency modules:**160```zig161const dep = b.dependency("lib", .{ .target = target, .optimize = optimize });162exe.root_module.addImport("lib", dep.module("lib"));163```164165**Compile-level methods deprecated:** `exe.linkSystemLibrary()`, `exe.addCSourceFiles()`,166`exe.addIncludePath()`, `exe.linkLibC()` are deprecated — use `exe.root_module.*` equivalents instead.167168See **[std.Build reference](references/std-build.md)** for complete build system documentation.169170## Critical: Container Initialization171172**Never use `.{}` for containers.** Use `.empty` or `.init`:173174```zig175// WRONG - deprecated176var list: std.ArrayList(u32) = .{};177var gpa: std.heap.DebugAllocator(.{}) = .{};178179// CORRECT - use .empty for empty collections180var list: std.ArrayList(u32) = .empty;181var map: std.AutoHashMapUnmanaged(u32, u32) = .empty;182183// CORRECT - use .init for stateful types with internal config184var gpa: std.heap.DebugAllocator(.{}) = .init;185var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);186```187188### Naming Changes189- **`std.ArrayListUnmanaged` → `std.ArrayList`** (Unmanaged is now default, old name deprecated)190- **`std.heap.GeneralPurposeAllocator` → `std.heap.DebugAllocator`** (GPA alias still works)191192**`std.BoundedArray` - REMOVED.** Use:193```zig194var buffer: [8]i32 = undefined;195var stack = std.ArrayList(i32).initBuffer(&buffer);196```197198## Critical: Format Strings (0.15.x)199200`{f}` required to call format methods:201```zig202// WRONG - ambiguous error203std.debug.print("{}", .{std.zig.fmtId("x")});204205// CORRECT206std.debug.print("{f}", .{std.zig.fmtId("x")});207```208209Format method signature changed:210```zig211// OLD - wrong212pub fn format(self: @This(), comptime fmt: []const u8, opts: std.fmt.FormatOptions, writer: anytype) !void213214// NEW - correct215pub fn format(self: @This(), writer: *std.Io.Writer) std.Io.Writer.Error!void216```217218## Breaking Changes (0.14.0+)219220### `@branchHint` replaces `@setCold`221```zig222// WRONG223@setCold(true);224225// CORRECT226@branchHint(.cold); // Must be first statement in block227```228229### `@export` takes pointer230```zig231// WRONG232@export(foo, .{ .name = "bar" });233234// CORRECT235@export(&foo, .{ .name = "bar" });236```237238### Inline asm clobbers are typed239```zig240// WRONG241: "rcx", "r11"242243// CORRECT244: .{ .rcx = true, .r11 = true }245```246247### `@fence` - REMOVED248Use stronger atomic orderings or RMW operations instead.249250## Decl Literals (0.14.0+)251252`.identifier` syntax works for declarations:253```zig254const S = struct {255 x: u32,256 const default: S = .{ .x = 0 };257 fn init(v: u32) S { return .{ .x = v }; }258};259260const a: S = .default; // S.default261const b: S = .init(42); // S.init(42)262const c: S = try .init(1); // works with try263```264265## Labeled Switch (0.14.0+)266267State machines use `continue :label`:268```zig269state: switch (initial) {270 .idle => continue :state .running,271 .running => if (done) break :state result else continue :state .running,272 .error => return error.Failed,273}274```275276## Non-exhaustive Enum Switch (0.15.x)277278Can mix explicit tags with `_` and `else`:279```zig280switch (value) {281 .a, .b => {},282 else => {}, // other named tags283 _ => {}, // unnamed integer values284}285```286287## Quick Fixes288289| Error | Fix |290|-------|-----|291| `no field 'root_source_file'` | Use `root_module = b.createModule(.{...})` |292| `use of undefined value` | Arithmetic on `undefined` is now illegal |293| `type 'f32' cannot represent integer` | Use float literal: `123_456_789.0` not `123_456_789` |294| `ambiguous format string` | Use `{f}` for format methods |295| `sanitize_c = true` | Type changed to `?std.zig.SanitizeC` — use `.full`, `.trap`, or `.off` |296| `std.fifo.LinearFifo` | Removed — use `std.Io.Reader`/`Writer` patterns |297| `posix.sendfile` | Removed — use `std.fs.File` writer `.sendFileAll()` |298| `std.fmt.Formatter` | Deprecated — renamed to `std.fmt.Alt` |299| `fmtSliceEscapeLower`/`Upper` | Use `std.ascii.hexEscape(bytes, .lower/.upper)` |300301## Language References302303Load these references when working with core language features:304305### Code Style306- **[Style Guide](references/style-guide.md)** - Official Zig naming conventions (TitleCase types, camelCase functions, snake_case variables), whitespace rules, doc comment guidance, redundancy avoidance, `zig fmt`307308### Language Basics & Built-ins309- **[Language Basics](references/language.md)** - Core language: types, control flow (if/while/for/switch), error handling (try/catch/errdefer), optionals, structs, enums, unions, pointers, slices, comptime, functions310- **[Built-in Functions](references/builtins.md)** - All `@` built-ins: type casts (@intCast, @bitCast, @ptrCast), arithmetic (@addWithOverflow, @divExact), bit ops (@clz, @popCount), memory (@memcpy, @sizeOf), atomics (@atomicRmw, @cmpxchgWeak), introspection (@typeInfo, @TypeOf, @hasDecl), SIMD (@Vector, @splat, @reduce), C interop (@cImport, @export)311312## Standard Library References313314Load these references when working with specific modules:315316### Memory & Slices317- **[std.mem](references/std-mem.md)** - Slice search/compare, split/tokenize, alignment, endianness, byte conversion318319### Text & Encoding320- **[std.fmt](references/std-fmt.md)** - Format strings, integer/float parsing, hex encoding, custom formatters, `{f}` specifier (0.15.x)321- **[std.ascii](references/std-ascii.md)** - ASCII character classification (isAlpha, isDigit), case conversion, case-insensitive comparison322- **[std.unicode](references/std-unicode.md)** - UTF-8/UTF-16 encoding/decoding, codepoint iteration, validation, WTF-8 for Windows323- **[std.base64](references/std-base64.md)** - Base64 encoding/decoding (standard, URL-safe, with/without padding)324325### Math & Random326- **[std.math](references/std-math.md)** - Floating-point ops, trig, overflow-checked arithmetic, constants, complex numbers, big integers327- **[std.Random](references/std-random.md)** - PRNGs (Xoshiro256, Pcg), CSPRNGs (ChaCha), random integers/floats/booleans, shuffle, distributions328- **[std.hash](references/std-hash.md)** - Non-cryptographic hash functions (Wyhash, XxHash, FNV, Murmur, CityHash), checksums (CRC32, Adler32), auto-hashing329330### SIMD & Vectorization331- **[std.simd](references/std-simd.md)** - SIMD vector utilities: optimal vector length, iota/repeat/join/interlace patterns, element shifting/rotation, parallel searching, prefix scans, branchless selection332333### Time & Timing334- **[std.time](references/std-time.md)** - Wall-clock timestamps, monotonic Instant/Timer, epoch conversions, calendar utilities (year/month/day), time unit constants335- **[std.Tz](references/std-tz.md)** - TZif timezone database parsing (RFC 8536), UTC offsets, DST rules, timezone abbreviations, leap seconds336337### Sorting & Searching338- **[std.sort](references/std-sort.md)** - Sorting algorithms (pdq, block, heap, insertion), binary search, min/max339340### Core Data Structures341- **[std.ArrayList](references/std-arraylist.md)** - Dynamic arrays, vectors, BoundedArray replacement342- **[std.HashMap / AutoHashMap](references/std-hashmap.md)** - Hash maps, string maps, ordered maps343- **[std.ArrayHashMap](references/std-array-hash-map.md)** - Insertion-order preserving hash map, array-style key/value access344- **[std.MultiArrayList](references/std-multi-array-list.md)** - Struct-of-arrays for cache-efficient struct storage345- **[std.SegmentedList](references/std-segmented-list.md)** - Stable pointers, arena-friendly, non-copyable types346- **[std.DoublyLinkedList / SinglyLinkedList](references/std-linked-list.md)** - Intrusive linked lists, O(1) insert/remove347- **[std.PriorityQueue](references/std-priority-queue.md)** - Binary heap, min/max extraction, task scheduling348- **[std.PriorityDequeue](references/std-priority-dequeue.md)** - Min-max heap, double-ended priority extraction349- **[std.Treap](references/std-treap.md)** - Self-balancing BST, ordered keys, min/max/predecessor350- **[std.bit_set](references/std-bit-set.md)** - Bit sets (Static, Dynamic, Integer, Array), set operations, iteration351- **[std.BufMap / BufSet](references/std-buf-map.md)** - String-owning maps and sets, automatic key/value memory management352- **[std.StaticStringMap](references/std-static-string-map.md)** - Compile-time optimized string lookup, perfect hash for keywords353- **[std.enums](references/std-enums.md)** - EnumSet, EnumMap, EnumArray: bit-backed enum collections354355### Allocators356- **[std.heap](references/std-allocators.md)** - Allocator selection guide, ArenaAllocator, DebugAllocator, FixedBufferAllocator, MemoryPool, SmpAllocator, ThreadSafeAllocator, StackFallbackAllocator, custom allocator implementation357358### I/O & Files359- **[std.io](references/std-io.md)** - Reader/Writer API (0.15.x): buffered I/O, streaming, binary data, format strings360- **[std.fs](references/std-fs.md)** - File system: files, directories, iteration, atomic writes, paths361- **[std.tar](references/std-tar.md)** - Tar archive reading/writing, extraction, POSIX ustar, GNU/pax extensions362- **[std.zip](references/std-zip.md)** - ZIP archive reading/extraction, ZIP64 support, store/deflate compression363- **[std.compress](references/std-compress.md)** - Compression: DEFLATE (gzip, zlib), Zstandard, LZMA, LZMA2, XZ decompression/compression364365### Networking366- **[std.http](references/std-http.md)** - HTTP client/server, TLS, connection pooling, compression, WebSocket367- **[std.net](references/std-net.md)** - TCP/UDP sockets, address parsing, DNS resolution368- **[std.Uri](references/std-uri.md)** - URI parsing/formatting (RFC 3986), percent-encoding/decoding, relative URI resolution369370### Process Management371- **[std.process](references/std-process.md)** - Child process spawning, environment variables, argument parsing, exec372373### OS-Specific APIs374- **[std.os](references/std-os.md)** - OS-specific APIs: Linux syscalls, io_uring, Windows NT APIs, WASI, direct platform access375- **[std.c](references/std-c.md)** - C ABI types and libc bindings: platform-specific types (fd_t, pid_t, timespec), errno values, socket/signal/memory types, fcntl/open flags, FFI with C libraries376377### Concurrency378- **[std.Thread](references/std-thread.md)** - Thread spawning, Mutex, RwLock, Condition, Semaphore, WaitGroup, thread pools379- **[std.atomic](references/std-atomic.md)** - Lock-free atomic operations: Value wrapper, fetch-and-modify (add/sub/and/or/xor), compare-and-swap, atomic ordering semantics, spin loop hints, cache line sizing380381### Patterns & Best Practices382- **[Zig Patterns](references/patterns.md)** - **Load when writing new code or reviewing code quality.** Comprehensive best practices extracted from the Zig standard library: quick patterns (memory/allocators, file I/O, HTTP, JSON, testing, build system) plus idiomatic code patterns covering syntax (closures, context pattern, options structs, destructuring), polymorphism (duck typing, generics, custom formatting, dynamic/static dispatch), safety (diagnostics, error payloads, defer/errdefer, compile-time assertions), and performance (const pointer passing)383- **[Code Review](references/code-review.md)** - **Load when reviewing Zig code.** Systematic checklist organized by confidence level: ALWAYS FLAG (removed features, changed syntax, API changes), FLAG WITH CONTEXT (exception safety bugs, missing flush, allocator issues), SUGGEST (style improvements). Includes migration examples for 0.14/0.15 breaking changes384385### Serialization386- **[std.json](references/std-json.md)** - JSON parsing, serialization, dynamic values, streaming, custom parse/stringify387- **[std.zon](references/std-zon.md)** - ZON (Zig Object Notation) parsing and serialization for build.zig.zon, config files, data interchange388389### Testing & Debug390- **[std.testing](references/std-testing.md)** - Unit test assertions and utilities391- **[std.debug](references/std-debug.md)** - Panic, assert, stack traces, hex dump, format specifiers392- **[std.log](references/std-log.md)** - Scoped logging with configurable levels and output393394### Metaprogramming395- **[Comptime Reference](references/comptime.md)** - Comptime fundamentals, type reflection (`@typeInfo`/`@Type`/`@TypeOf`), loop variants (`comptime for` vs `inline for`), branch elimination, type generation, comptime limitations396- **[std.meta](references/std-meta.md)** - Type introspection, field iteration, stringToEnum, generic programming397398### Compiler Utilities399- **[std.zig](references/std-zig.md)** - AST parsing, tokenization, source analysis, linters, formatters, ZON parsing400401### Security & Cryptography402- **[std.crypto](references/std-crypto.md)** - Hashing (SHA2, SHA3, Blake3), AEAD (AES-GCM, ChaCha20-Poly1305), signatures (Ed25519, ECDSA), key exchange (X25519), password hashing (Argon2, scrypt, bcrypt), secure random, timing-safe operations403404### Build System405- **[std.Build](references/std-build.md)** - Build system: build.zig, modules, dependencies, build.zig.zon, steps, options, testing, C/C++ integration406407### Interoperability408- **[C Interop](references/c-interop.md)** - Exporting C-compatible APIs: `export fn`, C calling convention, building static/dynamic libraries, creating headers, macOS universal binaries, XCFramework for Swift/Xcode, module maps409410## Audience411412| User Type | Usage |413|-----------|-------|414| **Zig 0.15 users** | Maintain legacy projects, understand 0.14→0.15 changes |415| **Migration users** | Replace deprecated APIs by following the Critical sections |416| **Compatibility checkers** | Verify existing code works under 0.15 |417418Customization: specify output format (full code / diff / snippet).419420## Gotchas4214221. **Always confirm the version first** — User code may come from any older version; run `zig version` to check4232. **build.zig API differences** — 0.15.x `addExecutable` uses `root_module` instead of the old `root_source_file`4243. **std.Io pattern** — 0.15 partially adopts the new `std.Io` pattern; old `std.io` is incompatible4254. **Container initialization** — `.{ }` for ArrayList etc. will error; use `.empty` or `.init`4265. **Format strings** — Custom formatters require `{f}` instead of `{}`4276. **Removed features** — `async`/`await`, `usingnamespace`, `@fence` are fully removed428429## FAQ430431**Q: Should I use `zig-0.15` or `zig-0.16`?**432A: For new projects, prefer `zig-0.16`. `zig-0.15` is retained for compatibility with existing 0.15 projects.433434**Q: What is the biggest difference between 0.15 and 0.14?**435A: The I/O API rewrite (std.io → std.Io) and the introduction of `root_module` in build.zig.436437**Q: How do I create an executable in 0.15?**438A: Use `b.addExecutable(.{ .name = "...", .root_module = b.createModule(...) })`.439