/zig-skills:zigfrom zig-skills
Provides up-to-date Zig patterns for v0.17.0-dev, covering breaking changes, build.zig, comptime, and quality tooling. Essential for avoiding outdated patterns from training data.
Ships in zig-skills. Installing the plugin adds it to Claude Code.
What the skill costs in Claude's context, stage by stage
Name and description: Claude knows it exists.
SKILL.md joins the conversation and stays.
Read when SKILL.md points to them.
Zig evolves rapidly. Training data contains outdated patterns that cause compilation errors. This skill documents breaking changes and correct modern patterns.
Version coverage: 0.17.0-dev (current master) — every 0.16.0 stable pattern below still holds, with migration notes from 0.15.x and 0.14.x and the 0.17 deltas in the section directly below.
Define types and function signatures before implementation. Let the compiler guide completeness:
Use Zig's type system to prevent invalid states at compile time:
anyerror — document exactly which failures can occurenum(u64) { _ } — prevent mixing up IDs (user_id vs order_id)@compileError() — catch invalid configurations at build timeLarger cohesive files are idiomatic in Zig. Keep related code together — tests alongside implementation, comptime generics at file scope, visibility controlled by pub. Split files only for genuinely separate concerns. The std library demonstrates this with files like std/mem.zig containing thousands of cohesive lines.
defer immediately after acquiring a resource — cleanup next to acquisitiongpa (caller must free), arena (bulk-free at boundary), scratch (never escapes)const over var — immutability signals intent and enables optimizationsStatus: 0.17.0 is unreleased as of mid-2026 — master/-dev only, no official release notes yet (0.17.0/release-notes.html 404s). The only migration source is the devlog. Every 0.16.0 pattern in the rest of this skill still applies — the items below are the additional deltas, verified against 0.17.0-dev.1158. Pin a dev build in build.zig.zon (.minimum_zig_version = "0.17.0-dev.NNN+hash"); anyzig fetches it.
Unchanged from 0.16 (verified present in 0.17-dev.956): std.Io.net, std.Io.Threaded, std.ArrayList (unmanaged default), std.debug.lockStderr, and the time/thread/crypto shims — all 0.16 sections below still hold.
b.args REMOVED → run_cmd.addPassthruArgs()The one change nearly every project needs. build.zig no longer observes CLI args (they now bypass build-script recompilation):
// WRONG (0.17) — error: no field named 'args' in struct 'Build'
if (b.args) |args| run_cmd.addArgs(args);
// CORRECT (0.17)
run_cmd.addPassthruArgs(); // forwards `zig build run -- a b c` to the spawned process
build.zig is now compiled in debug mode into a "configurer" that serializes the build graph to a binary file; a separately-cached "maker" executes it in release mode. Net effect: zig build invocation ~90% faster (zig build --help ~150ms → ~14ms) and changing build args no longer rebuilds build.zig. Mostly transparent — but it's why b.args had to go.
std.gpu → std.spirvGPU/shader namespace renamed (std/gpu.zig is gone, std/spirv.zig replaces it). std.gpu.executionMode() removed — execution modes now ride on the calling convention, and @SpirvType (new builtin) expresses samplers/images/runtime-arrays:
// SPIR-V entry points carry execution mode in the calling-convention payload (0.17)
export fn comp() callconv(.{ .spirv_kernel = .{ .x = 8, .y = 8, .z = 1 } }) void {}
// also: .spirv_vertex / .spirv_fragment / .spirv_task / .spirv_mesh
@bitCast semantics redesign — logical bit layout (proposal #19755)@bitCast now reinterprets a type's logical bits, not its in-memory bytes — so it is endian-agnostic (aggregates behave as little-endian on every target). Newly enables casts like [2]u3 → @Vector(3, u2); now allowed on enums; now disallowed on vectors-of-pointers. Code that relied on big-endian in-memory @bitCast of arrays/structs changes behavior.
zig-pkg/ + --forkFetched dependencies now land in a visible zig-pkg/ at project root (previously hidden in the global cache) — add it to .gitignore. New zig build --fork=<path> temporarily overrides a dependency without editing build.zig.zon.
std.Io.Evented (experimental)Event-driven Io backends added — io_uring (Linux) and Grand Central Dispatch (macOS) — alongside std.Io.Threaded. Still experimental.
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 - REMOVEDKeywords removed from language. Async I/O support is planned for future releases.
std.BoundedArray - REMOVEDUse std.ArrayList with initBuffer:
var buffer: [8]i32 = undefined;
var stack = std.ArrayList(i32).initBuffer(&buffer);
std.RingBuffer, std.fifo.LinearFifo - REMOVEDUse std.Io.Reader/std.Io.Writer ring buffers instead.
std.io.SeekableStream, std.io.BitReader, std.io.BitWriter - REMOVEDstd.fmt.Formatter - REMOVEDReplaced by std.fmt.Alt.
Arithmetic on undefined is now illegal. Only operators that can never trigger Illegal Behavior permit undefined as operand.
// WRONG - compile error in 0.15.x
var n: usize = undefined;
while (condition) : (n += 1) {} // ERROR: use of undefined value
// CORRECT - explicit initialization required
var n: usize = 0;
while (condition) : (n += 1) {}
// OK - space reservation (no arithmetic)
var buffer: [256]u8 = undefined;
std.net → std.Io.net (0.16)std.net is completely removed in 0.16. Replaced by std.Io.net, which requires an Io instance.
// WRONG (0.15) — std.net removed
const addr = std.net.Address.parseIp4(host, port) catch unreachable;
var server = addr.listen(.{ .reuse_address = true }) catch unreachable;
const conn = server.accept() catch continue;
defer conn.stream.close();
// CORRECT (0.16) — std.Io.net with Io instance
const addr = try std.Io.net.IpAddress.parse(host, port);
var server = try addr.listen(io, .{ .reuse_address = true });
const stream = try server.accept(); // returns Stream directly, no .stream wrapper
defer stream.close(io); // close() now takes io
// Create Io instance at startup, thread it through your program
var threaded = std.Io.Threaded.init(std.heap.c_allocator);
var io: std.Io = threaded.io();
// stream.handle → stream.socket.handle
std.posix.setsockopt(stream.socket.handle, ...);
// Io.net.Stream has NO .read() or .writeAll() — use raw C calls for blocking I/O:
extern "c" fn write(fd: c_int, buf: [*]const u8, n: usize) isize;
fn writeAll(stream: std.Io.net.Stream, data: []const u8) !void {
var rem = data;
while (rem.len > 0) {
const n = write(stream.socket.handle, rem.ptr, rem.len);
if (n <= 0) return error.BrokenPipe;
rem = rem[@intCast(n)..];
}
}
// std.posix.read() still works for reading
// connectUnixSocket, tcpConnectToHost — removed, use C externs:
extern "c" fn socket(domain: c_int, typ: c_int, proto: c_int) c_int;
extern "c" fn connect(fd: c_int, addr: *const anyopaque, len: u32) c_int;
// IMPORTANT: don't name local variables "socket" or "connect" — shadows extern
// std.net.has_unix_sockets → std.Io.net.has_unix_sockets
// std.posix.close → std.c.close (posix.close removed)
// std.posix.write/connect/socket — removed, use std.c.* or extern "c"
See std.net reference for complete networking documentation.
std.time.timestamp(), milliTimestamp(), microTimestamp(), nanoTimestamp() are removed. Use std.c.clock_gettime:
// WRONG (0.16) — removed
const secs = std.time.timestamp();
const ms = std.time.milliTimestamp();
// CORRECT — clock_gettime replacement
fn timestampSec() i64 {
var ts: std.c.timespec = undefined;
_ = std.c.clock_gettime(.REALTIME, &ts);
return ts.sec;
}
fn milliTimestamp() i64 {
var ts: std.c.timespec = undefined;
_ = std.c.clock_gettime(.REALTIME, &ts);
return @as(i64, ts.sec) * 1000 + @divTrunc(@as(i64, ts.nsec), 1_000_000);
}
Note: ts.nsec is signed — use @divTrunc, not / (0.16 enforces this for signed division).
std.time.ns_per_s, Instant, Timer — still present.
std.Thread.Mutex, std.Thread.Condition, std.Thread.sleep are removed. The 0.16 replacements (std.Io.Mutex/std.Io.Condition) require an Io instance. For library code without Io, use POSIX shims:
// WRONG (0.16)
var mutex: std.Thread.Mutex = .{};
mutex.lock();
// CORRECT — pthread shim (works without Io)
const PthreadMutex = struct {
inner: std.c.pthread_mutex_t = std.c.PTHREAD_MUTEX_INITIALIZER,
pub fn lock(m: *@This()) void { _ = std.c.pthread_mutex_lock(&m.inner); }
pub fn unlock(m: *@This()) void { _ = std.c.pthread_mutex_unlock(&m.inner); }
pub fn tryLock(m: *@This()) bool {
return @intFromEnum(std.c.pthread_mutex_trylock(&m.inner)) == 0;
}
};
// std.Thread.sleep → nanosleep
fn threadSleep(ns: u64) void {
const ts = std.c.timespec{
.sec = @intCast(ns / std.time.ns_per_s),
.nsec = @intCast(ns % std.time.ns_per_s),
};
_ = std.c.nanosleep(&ts, null);
}
std.Thread.spawn — unchanged.
See std.Thread reference for complete threading documentation including PthreadCondition.
// WRONG (0.16) — lockStderrWriter removed
const stderr = std.debug.lockStderrWriter();
defer std.debug.unlockStderr();
try stderr.print("msg\n", .{});
// CORRECT — lockStderr with buffer
var buf: [4096]u8 = undefined;
const held = std.debug.lockStderr(&buf);
defer std.debug.unlockStderr();
try held.file_writer.print("msg\n", .{});
std.crypto.random Removed (0.16)// WRONG (0.16) — removed
std.crypto.random.bytes(&nonce);
// CORRECT — platform-specific
extern "c" fn arc4random_buf(buf: *anyopaque, nbytes: usize) void;
arc4random_buf(&nonce, nonce.len); // macOS + Linux glibc 2.36+
// Linux-only (no glibc dependency):
_ = std.os.linux.getrandom(buf.ptr, buf.len, 0);
Note: std.posix.getrandom does NOT exist in 0.16.
Local constants cannot shadow module-level extern declarations:
extern "c" fn socket(...) c_int;
fn myConnect() !void {
// WRONG — "local constant shadows declaration of socket"
const socket = blk: { ... };
// CORRECT — use different name
const sock_fd = blk: { ... };
}
The entire std.io API changed. New std.Io.Writer and std.Io.Reader are non-generic with buffer in the interface.
// 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 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);
var buf: [256]u8 = undefined;
var w: std.Io.Writer = .fixed(&buf);
try w.print("Hello {s}", .{"world"});
const result = w.buffered(); // "Hello world"
var r: std.Io.Reader = .fixed("hello\nworld");
const line = (try r.takeDelimiter('\n')).?; // "hello" (returns null at EOF)
Removed: 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) callstd.Io.Writer.Allocatingstd.io.fixedBufferStream Removed (0.16)// WRONG (0.16) — std.io (lowercase) removed entirely
var buf: [512]u8 = undefined;
var stream = std.io.fixedBufferStream(&buf);
try std.fmt.format(stream.writer(), "{d}", .{value});
const result = stream.getWritten();
// CORRECT — use std.fmt.bufPrint directly
var buf: [512]u8 = undefined;
const result = try std.fmt.bufPrint(&buf, "{d}", .{value});
// WRONG — *std.io.Writer (lowercase)
fn drain(w: *std.io.Writer) error{WriteFailed}!usize { ... }
// CORRECT — *std.Io.Writer (capital)
fn drain(w: *std.Io.Writer) error{WriteFailed}!usize { ... }
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);
Libraries: addSharedLibrary → addLibrary with .linkage:
// WRONG - removed function
const lib = b.addSharedLibrary(.{ .name = "mylib", ... });
// CORRECT - unified addLibrary with linkage field
const lib = b.addLibrary(.{
.name = "mylib",
.linkage = .dynamic, // or .static (default)
.root_module = b.createModule(.{
.root_source_file = b.path("src/lib.zig"),
.target = target,
.optimize = optimize,
}),
});
Adding dependency modules:
const dep = b.dependency("lib", .{ .target = target, .optimize = optimize });
exe.root_module.addImport("lib", dep.module("lib"));
Compile.* Methods Moved to Module.* (0.16)In 0.16, methods like addIncludePath, addLibraryPath, linkSystemLibrary, addCSourceFile moved from the Compile step to the module:
// WRONG (0.16) — methods no longer on Compile
lib.addIncludePath(.{ .cwd_relative = path });
lib.linkSystemLibrary("foo");
lib.addCSourceFile(.{ .file = b.path("shim.c"), .flags = &.{} });
// CORRECT — use root_module
lib.root_module.addIncludePath(.{ .cwd_relative = path });
lib.root_module.linkSystemLibrary("foo", .{}); // note: now takes options struct
lib.root_module.addCSourceFile(.{ .file = b.path("shim.c"), .flags = &.{} });
Common misleading error: no field or member function named 'addIncludePath' in 'Build.Step.Compile'. The note about .* is wrong — the fix is lib.root_module.addIncludePath(...).
See std.Build reference for complete build system documentation.
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);
The old std.ArrayList (with allocator stored in struct) is now std.array_list.Managed.
The new std.ArrayList is unmanaged — no allocator field, pass allocator to every method:
// NEW default: unmanaged (no allocator field)
var list: std.ArrayList(u32) = .empty;
try list.append(allocator, 42);
list.deinit(allocator);
// If you want old behavior (allocator in struct), use Managed:
var list = std.array_list.Managed(u32).init(allocator);
try list.append(42); // no allocator arg needed
list.deinit();
Same pattern applies — unmanaged variants require allocator per operation:
// Unmanaged (no internal allocator)
var map: std.StringHashMapUnmanaged(u32) = .empty;
try map.put(allocator, "key", 42);
map.deinit(allocator);
// Managed (stores allocator internally)
var map = std.StringHashMap(u32).init(allocator);
try map.put("key", 42);
map.deinit();
In 0.16, .{} zero-init no longer works for ArrayListUnmanaged — explicit fields required:
// WRONG (0.16) — .{} no longer zero-inits correctly
._list = .{},
// CORRECT — explicit fields
._list = .{ .items = &.{}, .capacity = 0 },
std.ArrayListUnmanaged -> std.ArrayList (Unmanaged is now default, old name deprecated)std.heap.GeneralPurposeAllocator -> std.heap.DebugAllocator (GPA alias still works)// WRONG - old API
const Node = std.DoublyLinkedList(MyData).Node;
// CORRECT - non-generic, use @fieldParentPtr
const MyNode = struct {
node: std.DoublyLinkedList.Node,
data: MyData,
};
// Access: const my_node = @fieldParentPtr("node", node_ptr);
// WRONG - direct field access removed
if (result.term.Exited != 0) {}
// CORRECT - pattern match
switch (result.term) {
.exited => |code| if (code != 0) { /* handle */ },
else => {},
}
{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
@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" });
// WRONG
: "rcx", "r11"
// CORRECT
: .{ .rcx = true, .r11 = true }
@fence - REMOVEDUse stronger atomic orderings or RMW operations instead.
@typeInfo fields now lowercase// WRONG - old PascalCase (compile error)
if (@typeInfo(T) == .Struct) { ... }
if (@typeInfo(T) == .Slice) { ... }
if (@typeInfo(T) == .Int) { ... }
// CORRECT - lowercase, keywords escaped with @""
if (@typeInfo(T) == .@"struct") { ... }
if (@typeInfo(T) == .@"enum") { ... }
if (@typeInfo(T) == .@"union") { ... }
if (@typeInfo(T) == .@"opaque") { ... }
if (@typeInfo(T) == .slice) { ... }
if (@typeInfo(T) == .int) { ... }
if (@typeInfo(T) == .bool) { ... }
if (@typeInfo(T) == .pointer) { ... }
// Accessing fields:
const fields = @typeInfo(T).@"struct".fields;
const tag_type = @typeInfo(T).@"enum".tag_type;
.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
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,
}
Can mix explicit tags with _ and else:
switch (value) {
.a, .b => {},
else => {}, // other named tags
_ => {}, // unnamed integer values
}
HTTP client/server completely restructured — depends only on I/O streams, not networking:
// Server now takes Reader/Writer interfaces, not connection directly
var recv_buffer: [4000]u8 = undefined;
var send_buffer: [4000]u8 = undefined;
var conn_reader = connection.stream.reader(&recv_buffer);
var conn_writer = connection.stream.writer(&send_buffer);
var server = std.http.Server.init(
conn_reader.interface(),
&conn_writer.interface,
);
Note: HTTP client API is still rapidly evolving. For stability-critical code, consider shelling out to curl.
| Error | Fix |
|---|---|
no field 'root_source_file' | Use root_module = b.createModule(.{...}) |
'std.net' has no member 'Stream' | Networking moved: use std.Io.net.Stream (0.16) |
'std.net' has no member 'Address' | Use std.Io.net.IpAddress.parse(host, port) (0.16) |
no field 'addIncludePath' in 'Compile' | Methods moved: lib.root_module.addIncludePath(...) (0.16) |
'timestamp' not found in 'std.time' | Removed: use std.c.clock_gettime(.REALTIME, &ts) (0.16) |
'Mutex' not found in 'std.Thread' | Removed: use POSIX PthreadMutex shim or std.Io.Mutex (0.16) |
'random' not found in 'std.crypto' | Removed: use arc4random_buf or std.os.linux.getrandom (0.16) |
'lockStderrWriter' not found | Renamed: use std.debug.lockStderr(&buf) (0.16) |
local constant shadows declaration | 0.16 forbids local names matching module-level extern fn — rename local |
signed integer division | Use @divTrunc(a, b) not a / b for signed integers (0.16) |
no field 'close' in 'posix' | std.posix.close removed: use _ = std.c.close(fd) (0.16) |
use of undefined value | Arithmetic on undefined is now illegal — initialize explicitly |
type 'f32' cannot represent integer | Use float literal: 123_456_789.0 not 123_456_789 |
ambiguous format string | Use {f} for format methods |
no field 'append' on ArrayList | Pass allocator: list.append(allocator, val) (unmanaged default) |
expected 2 arguments, found 1 on ArrayList | Add allocator param: .append(allocator, val), .deinit(allocator) |
BoundedArray not found | Use std.ArrayList(T).initBuffer(&buf) |
GenericWriter/GenericReader | Use std.Io.Writer/std.Io.Reader |
missing .flush() — no output | Always call try writer.flush() after writing |
enum has no member named 'Struct' | @typeInfo fields now lowercase: .@"struct", .slice, .int |
no field named 'encode' on base64 | Use std.base64.standard.Encoder.encode() |
no field named 'open' on HTTP | Use client.request() or client.fetch() |
expected error union, found Signature | Ed25519.Signature.fromBytes() doesn't return error — remove try |
addSharedLibrary not found | Use b.addLibrary(.{ .linkage = .dynamic, ... }) |
no field named 'args' in struct 'Build' | Removed in 0.17: run_cmd.addPassthruArgs() instead of `if (b.args) |
'std' has no member named 'gpu' | Renamed in 0.17: std.spirv; executionMode() → calling-convention payload |
ZLS build: Zig version ... is not yet supported | ZLS pins an exact dev Zig — build with the README-pinned version: zig <pinned> build |
After writing or modifying Zig code, verify with this sequence:
zig build — catch compilation errors, match against Quick Fixes abovezig build test — run unit testszig build -Doptimize=ReleaseFast test — detect undefined behavior (UB checks enabled in optimized builds)Development speed tips:
zig build --watch -fincremental — incremental compilation, rebuilds on file changedefer/errdefer cleanup — place cleanup immediately after resource acquisitionanyerror instead of specific error sets — explicit sets document failure modeserrdefer after allocations in multi-step init — partial construction leaks:0 sentinel slices: [:0]const u8anytype when comptime T: type works — explicit types produce clearer errorsconst log = std.log.scoped(.my_module); for filterable loggingProduction Zig codebases worth studying:
Load these references when working with core language features:
zig fmt@ 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)Load these references when working with specific modules:
{f} specifier (0.15.x)@Vector: calling LLVM target intrinsics (extern fn @"llvm.x86.avx2.pmadd.wd" / @"llvm.aarch64.neon.udot…") for ops with no @Vector form (udot, vpsadbw, vpmaddubsw); why this beats inline asm (optimizer-transparent vs opaque); perf gotchas (natural result layout, comptime mode params, manual unroll); cross-arch validation via Rosetta / static-musl + scp / asm-diffenum(u32) newtype handles), booleans out of band, struct-of-arrays via MultiArrayList, sparse data in hash maps, encodings instead of fat tagged unions, and constraining ranges/dropping derivable data. Includes the compiler case study (token 64→5 B, AST 120→15.6 B, ZIR 54→20.3 B; −22% then −39% wall-clock) and an anti-pattern checklist@typeInfo/@Type/@TypeOf), loop variants (comptime for vs inline for), branch elimination, type generation, comptime limitationsunused-decls covers only constants), duplicate detection (jscpd + the --max-lines trap), zlint (⚠️ Homebrew's zlint is an X.509 linter), and the built-in fuzzer (*Smith signature, corpus economics, coverage plateaus)export fn, C calling convention, building static/dynamic libraries, creating headers, macOS universal binaries, XCFramework for Swift/Xcode, module mapsZig ships none of these. Full details and measurements: Quality Tooling. The traps that silently produce a green result:
kcov works on Zig binaries with no instrumentation, macOS included. Use codecov.json for per-line data ("taken/total" strings); coverage.json is summary-only.unused-decls covers constants/variables only — resolving a call through anytype would mean monomorphising. Rename the definition and rebuild to prove it; a syntactic "identifier occurs once" prefilter is instant and can only err by missing.jscpd --max-lines defaults to 1000 and skips longer files silently. Pass --format c --formats-exts "c:zig" --max-lines 100000.zlint in Homebrew is zmap/zlint, an X.509 certificate linter. The Zig one is DonIsaac/zlint, release binary only. Its config replaces the rule set rather than extending it.testOne takes *std.testing.Smith, not []const u8 (see std.testing). The persisted corpus is what makes coverage guidance pay off; from an empty corpus it is no better than random. Two concurrent runs abort and leave a bogus crash artifact.IDE support via Language Server Protocol. Provides autocomplete, go-to-definition, hover docs, diagnostics.
Version matching rule: Use ZLS release matching your Zig release (0.15.x ZLS for 0.15.x Zig). Nightly Zig needs nightly ZLS.
Nightly/-dev gotcha (learned the hard way): ZLS master pins an exact Zig dev build (see minimum_zig_version in its build.zig.zon and the "default branch targets 0.17.0-dev.NNN" line in its README), and build.zig hard-errors on Zig newer than its supported window (The used Zig version ... is not yet supported by ZLS). Two traps:
master often lags the latest Zig master by weeks, so the newest downloadable Zig (zig version) may be rejected by ZLS.master build plus tagged releases — older -dev builds get pruned and 404 on download. The exact version ZLS pins may or may not still be downloadable.Build ZLS against its README-pinned Zig explicitly (anyzig will fetch it if still available):
cd zls
git pull # ZLS master targets newest supported Zig
grep -n "default branch.*targets\|0\.1" README.md # find the pinned 0.NN.0-dev.NNN+hash
zig <pinned-version> build -Doptimize=ReleaseSafe # e.g. zig 0.17.0-dev.387+31f157d80 build
If the pinned build 404s, either use a Zig version inside ZLS's supported range (build.zig rejects >= max), or wait for ZLS to bump its pin to a currently-downloadable Zig.
Installation:
# VS Code: install "Zig Language" extension (includes ZLS)
# Manual / other editors:
# Download from https://github.com/zigtools/zls/releases
# Or build from source:
git clone https://github.com/zigtools/zls
cd zls && git checkout 0.15.0 # match your Zig version
zig build -Doptimize=ReleaseSafe
# Configure:
zls --config
Editor support: VS Code, Neovim (nvim-lspconfig), Helix, JetBrains, Emacs (lsp-mode), Sublime Text, Kate.
Key features:
@import("") stringsstd and builtin module path completionsManage multiple Zig versions side-by-side. Useful for migrating between versions.
Source: https://github.com/marler8997/zigup
Installation:
brew install zigup
Usage:
zigup fetch 0.15.2 # download without changing default
zigup fetch 0.16.0 # download without changing default
zigup list # show installed versions
zigup 0.16.0 # set as default
zigup run 0.15.2 build # run specific version without changing default
zigup run 0.16.0 build test # test with specific version
zigup clean 0.15.2 # remove old version
Migration workflow:
zigup run 0.16.0 zig build 2>&1 | head -40 # try build with new version
# fix errors, re-run until clean
zigup 0.16.0 # promote to default
Universal Zig version manager — run any Zig version from any project. Replaces manual version switching.
Source: https://github.com/marler8997/anyzig
How it works:
minimum_zig_version from build.zig.zon (searches up directory tree)zig transparentlyInstallation:
brew install anyzig
For other platforms, see https://github.com/marler8997/anyzig
Usage:
# Automatic — reads build.zig.zon minimum_zig_version:
cd myproject && zig build
# Manual version override:
zig 0.13.0 build-exe myproject.zig
zig 0.15.2 build
# Mach engine versions supported:
# Reads .mach_zig_version from build.zig.zon
# Format: 2024.10.0-mach
# anyzig-specific commands:
zig any --help
build.zig.zon version field:
.{
.name = .myproject,
.version = "0.1.0",
.minimum_zig_version = "0.15.2",
// ...
}
Two complementary angles: deterministic allocation counts (no sampling noise, immune to inlining) and CPU sampling (where wall-time goes).
Allocation profiling — wrap the allocator, count calls. The single best signal for "is this parser/codec alloc-bound?". A counting Allocator vtable wrapper over a child allocator tallies alloc/resize/remap/free + bytes + peak-live. Run one parse, print the tally. Deterministic and reproducible — e.g. it instantly reveals a "dupe-per-string" parser doing ~1 malloc per token (thousands of allocs for a small file) vs an arena parser doing a handful. Caveat: an arena-based parser hides logical allocations behind a few big chunk mallocs — to count logical requests, wrap the arena's allocator, not its backing allocator.
const Counting = struct {
child: std.mem.Allocator,
allocs: usize = 0, bytes: usize = 0, live: usize = 0, peak: usize = 0,
pub fn allocator(self: *Counting) std.mem.Allocator {
return .{ .ptr = self, .vtable = &.{ .alloc = a, .resize = r, .remap = rm, .free = f } };
}
fn a(ctx: *anyopaque, len: usize, al: std.mem.Alignment, ra: usize) ?[*]u8 {
const s: *Counting = @ptrCast(@alignCast(ctx));
const p = s.child.rawAlloc(len, al, ra) orelse return null;
s.allocs += 1; s.bytes += len; s.live += len; s.peak = @max(s.peak, s.live);
return p;
}
// resize/remap update live; free does live -= buf.len; all delegate to s.child.raw*()
};
CPU sampling — Instruments via xctrace (works; needs dSYM). instruments GUI launcher is gone in recent Xcode; use the xctrace CLI. The critical step is dsymutil: with a dSYM, xctrace export symbolicates even inlined frames, so a ReleaseFast recursive-descent parser (everything inlined into main) still shows per-function attribution. Without it you get a flat main+0xNNNN blob — which is also why bare /usr/bin/sample is nearly useless on optimized Zig.
zig build # do NOT strip; keep debug info
dsymutil ./zig-out/bin/bench # -> bench.dSYM (symbolicates inlined frames)
xctrace record --template 'Time Profiler' --time-limit 5s \
--output prof.trace --launch -- ./zig-out/bin/bench <args> # or: --attach <pid>
open prof.trace # GUI: call tree / flame graph / source
# CLI export (XML only, slow):
xctrace export --input prof.trace \
--xpath '/trace-toc/run[@number="1"]/data/table[@schema="time-profile"]' --output tp.xml
# then aggregate symbol names out of the backtraces (grep/sort/uniq)
Gotchas:
noinline temporarily.xctrace export is XML-only and slow; for interactive use prefer open prof.trace.Alternatives (often nicer on Apple Silicon):
samply record ./bin <args> — opens the Firefox Profiler UI (call tree, flamegraph, source). brew install samply / cargo install samply.poop ./old ./new — A/B compare two binaries on hardware counters (instructions, branch misses, cache misses). Ideal for before/after on an optimization. Linux-native; on macOS counters are limited.See Production Patterns (counting allocators) for the full instrumented-allocator pattern.
references/builtins.md (opens in a new tab)references/c-interop.md (opens in a new tab)references/code-review.md (opens in a new tab)references/comptime.md (opens in a new tab)references/data-oriented-design.md (opens in a new tab)references/language.md (opens in a new tab)references/mcp-server-patterns.md (opens in a new tab)references/patterns.md (opens in a new tab)references/production-patterns.md (opens in a new tab)references/quality-tooling.md (opens in a new tab)references/simd-intrinsics.md (opens in a new tab)references/std-allocators.md (opens in a new tab)references/std-array-hash-map.md (opens in a new tab)references/std-arraylist.md (opens in a new tab)references/std-ascii.md (opens in a new tab)references/std-atomic.md (opens in a new tab)references/std-base64.md (opens in a new tab)references/std-bit-set.md (opens in a new tab)references/std-buf-map.md (opens in a new tab)references/std-build.md (opens in a new tab)What SKILL.md sets; muted values are Claude Code's defaults
Three short reads, in order
zig, zig-language, comptime, build-system, breaking-changes, code-quality
Claude Code refuses to install this plugin
.claude-plugin/plugin.json: author: Invalid input: expected object, received string, skills: Invalid input
Checked against Claude Code 2.1.332's install rules. The listing below is what the repository ships; Claude Code cannot install it as published.
Other plugins' skills for the same job