--- name: zig description: Zig language reference and best practices — comptime patterns, allocator-based memory management, error sets, tagged unions, stdlib usage. Includes how to fetch std source and language reference. license: MIT --- # Zig Documentation ## Fetch Standard Library Source ```bash # Module source with doc comments curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/.zig" # Common modules curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/log.zig" curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/mem.zig" curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/fs.zig" curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/heap.zig" curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/debug.zig" curl -sL "https://raw.githubusercontent.com/ziglang/zig/master/lib/std/testing.zig" ``` ## Fetch Language Reference ```bash pandoc -f html -t plain "https://ziglang.org/documentation/master/" ``` ## Version-Specific ```bash # 0.14.0 release curl -sL "https://raw.githubusercontent.com/ziglang/zig/0.14.0/lib/std/log.zig" pandoc -f html -t plain "https://ziglang.org/documentation/0.14.0/" ``` --- # Zig Best Practices ## Type-First Development ### Make Illegal States Unrepresentable **Tagged unions:** ```zig const RequestState = union(enum) { idle, loading, success: []const u8, failure: anyerror, }; fn handleState(state: RequestState) void { switch (state) { .idle => {}, .loading => showSpinner(), .success => |data| render(data), .failure => |err| showError(err), } } ``` **Explicit error sets:** ```zig const ParseError = error{ InvalidSyntax, UnexpectedToken, EndOfInput, }; fn parse(input: []const u8) ParseError!Ast { } ``` **Distinct types:** ```zig const UserId = enum(u64) { _ }; const OrderId = enum(u64) { _ }; ``` --- ## Memory Management **Pass allocators explicitly:** ```zig fn processData(allocator: std.mem.Allocator, input: []const u8) ![]u8 { const result = try allocator.alloc(u8, input.len * 2); errdefer allocator.free(result); return result; } ``` **Arena allocator for batch operations:** ```zig fn processBatch(items: []const Item) !void { var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator); defer arena.deinit(); const allocator = arena.allocator(); // All allocations freed when arena deinits } ``` --- ## Error Handling **Specific error sets:** ```zig const ConfigError = error{ FileNotFound, ParseError, InvalidFormat, }; fn loadConfig(path: []const u8) ConfigError!Config { } ``` **errdefer for cleanup:** ```zig fn createResource(allocator: std.mem.Allocator) !*Resource { const resource = try allocator.create(Resource); errdefer allocator.destroy(resource); return resource; } ``` --- ## Logging **Scoped logger:** ```zig const log = std.log.scoped(.widgets); pub fn createWidget(name: []const u8) !Widget { log.debug("creating widget: {s}", .{name}); return widget; } ``` --- ## Comptime Patterns **Generic function:** ```zig fn max(comptime T: type, a: T, b: T) T { return if (a > b) a else b; } ``` **Compile-time validation:** ```zig fn Buffer(comptime size: usize) type { if (size == 0) { @compileError("buffer size must be greater than 0"); } return struct { data: [size]u8 = undefined }; } ``` --- ## Optionals **Safe handling:** ```zig fn findWidget(id: u32) ?*Widget { } fn processWidget(id: u32) !void { const widget = findWidget(id) orelse return error.WidgetNotFound; try widget.process(); } ``` --- ## Module Structure - Larger cohesive files are idiomatic in Zig - Keep tests alongside implementation - Split only for genuinely separate concerns --- ## Guidelines - Use `errdefer` for cleanup on error paths - Handle all switch branches; use `else` or `_` for defaults - Prefer `const` over `var` - Avoid `anytype`; use `comptime T: type` - Use `std.testing.allocator` in tests for leak detection --- ## References - https://ziglang.org/documentation/master/ - https://zig.guide/