[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M6EHFJ5G8RY7BN4FTZFMSJTZ":3,"skill-same:01M6EHFJ5G8RY7BN4FTZFMSJTZ":114},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":34,"linkOnly":35,"markdownContent":36,"markdownBody":37,"frontMatter":38,"refName":39,"commitSha":40,"skillDirectory":41,"forksCount":42,"repositoryHtmlUrl":43,"repositoryHomepageUrl":44,"ownerHtmlUrl":45,"ownerBlogUrl":6,"ownerDescription":46,"updatedAt":47,"install":48,"resources":61},"01M6EHFJ5G8RY7BN4FTZFMSJTZ","zig-best-practices",null,"Provides Zig patterns for type-first development with tagged unions, explicit error sets, comptime validation, and memory management. Must use when reading or writing Zig files.","ComeOnOliver\u002Fskillshub","ComeOnOliver","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F43215937?v=4","01M6E5JNFECJAAVFE0W7SMWWD2","Haoran Shu","01M6E5JNNDQS7AJZDYFQ8TPZCK",67,"MIT","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002FSKILL.md",[],[19,20,21,22,23,24,25,26,27,28,29,30,31,32,33],"best practices","zig","zig best practices","writing","memory","development","validation","first","management","use","files","patterns","memory management","type","error","2026-11-10 10:12:30",false,"---\nname: zig-best-practices\ndescription: Provides Zig patterns for type-first development with tagged unions, explicit error sets, comptime validation, and memory management. Must use when reading or writing Zig files.\n---\n\n# Zig Best Practices\n\n## Type-First Development\n\nTypes define the contract before implementation. Follow this workflow:\n\n1. **Define data structures** - structs, unions, and error sets first\n2. **Define function signatures** - parameters, return types, and error unions\n3. **Implement to satisfy types** - let the compiler guide completeness\n4. **Validate at comptime** - catch invalid configurations during compilation\n\n### Make Illegal States Unrepresentable\n\nUse Zig's type system to prevent invalid states at compile time.\n\n**Tagged unions for mutually exclusive states:**\n```zig\n\u002F\u002F Good: only valid combinations possible\nconst RequestState = union(enum) {\n    idle,\n    loading,\n    success: []const u8,\n    failure: anyerror,\n};\n\nfn handleState(state: RequestState) void {\n    switch (state) {\n        .idle => {},\n        .loading => showSpinner(),\n        .success => |data| render(data),\n        .failure => |err| showError(err),\n    }\n}\n\n\u002F\u002F Bad: allows invalid combinations\nconst RequestState = struct {\n    loading: bool,\n    data: ?[]const u8,\n    err: ?anyerror,\n};\n```\n\n**Explicit error sets for failure modes:**\n```zig\n\u002F\u002F Good: documents exactly what can fail\nconst ParseError = error{\n    InvalidSyntax,\n    UnexpectedToken,\n    EndOfInput,\n};\n\nfn parse(input: []const u8) ParseError!Ast {\n    \u002F\u002F implementation\n}\n\n\u002F\u002F Bad: anyerror hides failure modes\nfn parse(input: []const u8) anyerror!Ast {\n    \u002F\u002F implementation\n}\n```\n\n**Distinct types for domain concepts:**\n```zig\n\u002F\u002F Prevent mixing up IDs of different types\nconst UserId = enum(u64) { _ };\nconst OrderId = enum(u64) { _ };\n\nfn getUser(id: UserId) !User {\n    \u002F\u002F Compiler prevents passing OrderId here\n}\n\nfn createUserId(raw: u64) UserId {\n    return @enumFromInt(raw);\n}\n```\n\n**Comptime validation for invariants:**\n```zig\nfn Buffer(comptime size: usize) type {\n    if (size == 0) {\n        @compileError(\"buffer size must be greater than 0\");\n    }\n    if (size > 1024 * 1024) {\n        @compileError(\"buffer size exceeds 1MB limit\");\n    }\n    return struct {\n        data: [size]u8 = undefined,\n        len: usize = 0,\n    };\n}\n```\n\n**Non-exhaustive enums for extensibility:**\n```zig\n\u002F\u002F External enum that may gain variants\nconst Status = enum(u8) {\n    active = 1,\n    inactive = 2,\n    pending = 3,\n    _,\n};\n\nfn processStatus(status: Status) !void {\n    switch (status) {\n        .active => {},\n        .inactive => {},\n        .pending => {},\n        _ => return error.UnknownStatus,\n    }\n}\n```\n\n## Module Structure\n\nLarger cohesive files are idiomatic in Zig. Keep related code together: tests alongside implementation, comptime generics at file scope, public\u002Fprivate controlled by `pub`. Split only when a file handles genuinely separate concerns. The standard library demonstrates this pattern with files like `std\u002Fmem.zig` containing 2000+ lines of cohesive memory operations.\n\n## Instructions\n\n- Return errors with context using error unions (`!T`); every function returns a value or an error. Explicit error sets document failure modes.\n- Use `errdefer` for cleanup on error paths; use `defer` for unconditional cleanup. This prevents resource leaks without try-finally boilerplate.\n- Handle all branches in `switch` statements; include an `else` clause that returns an error or uses `unreachable` for truly impossible cases.\n- Pass allocators explicitly to functions requiring dynamic memory; prefer `std.testing.allocator` in tests for leak detection.\n- Prefer `const` over `var`; prefer slices over raw pointers for bounds safety. Immutability signals intent and enables optimizations.\n- Avoid `anytype`; prefer explicit `comptime T: type` parameters. Explicit types document intent and produce clearer error messages.\n- Use `std.log.scoped` for namespaced logging; define a module-level `log` constant for consistent scope across the file.\n- Add or update tests for new logic; use `std.testing.allocator` to catch memory leaks automatically.\n\n## Examples\n\nExplicit failure for unimplemented logic:\n```zig\nfn buildWidget(widget_type: []const u8) !Widget {\n    return error.NotImplemented;\n}\n```\n\nPropagate errors with try:\n```zig\nfn readConfig(path: []const u8) !Config {\n    const file = try std.fs.cwd().openFile(path, .{});\n    defer file.close();\n    const contents = try file.readToEndAlloc(allocator, max_size);\n    return parseConfig(contents);\n}\n```\n\nResource cleanup with errdefer:\n```zig\nfn createResource(allocator: std.mem.Allocator) !*Resource {\n    const resource = try allocator.create(Resource);\n    errdefer allocator.destroy(resource);\n\n    resource.* = try initializeResource();\n    return resource;\n}\n```\n\nExhaustive switch with explicit default:\n```zig\nfn processStatus(status: Status) ![]const u8 {\n    return switch (status) {\n        .active => \"processing\",\n        .inactive => \"skipped\",\n        _ => error.UnhandledStatus,\n    };\n}\n```\n\nTesting with memory leak detection:\n```zig\nconst std = @import(\"std\");\n\ntest \"widget creation\" {\n    const allocator = std.testing.allocator;\n    var list: std.ArrayListUnmanaged(u32) = .empty;\n    defer list.deinit(allocator);\n\n    try list.append(allocator, 42);\n    try std.testing.expectEqual(1, list.items.len);\n}\n```\n\n## Memory Management\n\n- Pass allocators explicitly; never use global state for allocation. Functions declare their allocation needs in parameters.\n- Use `defer` immediately after acquiring a resource. Place cleanup logic next to acquisition for clarity.\n- Prefer arena allocators for temporary allocations; they free everything at once when the arena is destroyed.\n- Use `std.testing.allocator` in tests; it reports leaks with stack traces showing allocation origins.\n\n### Examples\n\nAllocator as explicit parameter:\n```zig\nfn processData(allocator: std.mem.Allocator, input: []const u8) ![]u8 {\n    const result = try allocator.alloc(u8, input.len * 2);\n    errdefer allocator.free(result);\n\n    \u002F\u002F process input into result\n    return result;\n}\n```\n\nArena allocator for batch operations:\n```zig\nfn processBatch(items: []const Item) !void {\n    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n    defer arena.deinit();\n    const allocator = arena.allocator();\n\n    for (items) |item| {\n        const processed = try processItem(allocator, item);\n        try outputResult(processed);\n    }\n    \u002F\u002F All allocations freed when arena deinits\n}\n```\n\n## Logging\n\n- Use `std.log.scoped` to create namespaced loggers; each module should define its own scoped logger for filtering.\n- Define a module-level `const log` at the top of the file; use it consistently throughout the module.\n- Use appropriate log levels: `err` for failures, `warn` for suspicious conditions, `info` for state changes, `debug` for tracing.\n\n### Examples\n\nScoped logger for a module:\n```zig\nconst std = @import(\"std\");\nconst log = std.log.scoped(.widgets);\n\npub fn createWidget(name: []const u8) !Widget {\n    log.debug(\"creating widget: {s}\", .{name});\n    const widget = try allocateWidget(name);\n    log.debug(\"created widget id={d}\", .{widget.id});\n    return widget;\n}\n\npub fn deleteWidget(id: u32) void {\n    log.info(\"deleting widget id={d}\", .{id});\n    \u002F\u002F cleanup\n}\n```\n\nMultiple scopes in a codebase:\n```zig\n\u002F\u002F In src\u002Fdb.zig\nconst log = std.log.scoped(.db);\n\n\u002F\u002F In src\u002Fhttp.zig\nconst log = std.log.scoped(.http);\n\n\u002F\u002F In src\u002Fauth.zig\nconst log = std.log.scoped(.auth);\n```\n\n## Comptime Patterns\n\n- Use `comptime` parameters for generic functions; type information is available at compile time with zero runtime cost.\n- Prefer compile-time validation over runtime checks when possible. Catch errors during compilation rather than in production.\n- Use `@compileError` for invalid configurations that should fail the build.\n\n### Examples\n\nGeneric function with comptime type:\n```zig\nfn max(comptime T: type, a: T, b: T) T {\n    return if (a > b) a else b;\n}\n```\n\nCompile-time validation:\n```zig\nfn createBuffer(comptime size: usize) [size]u8 {\n    if (size == 0) {\n        @compileError(\"buffer size must be greater than 0\");\n    }\n    return [_]u8{0} ** size;\n}\n```\n\n## Avoiding anytype\n\n- Prefer `comptime T: type` over `anytype`; explicit type parameters document expected constraints and produce clearer errors.\n- Use `anytype` only when the function genuinely accepts any type (like `std.debug.print`) or for callbacks\u002Fclosures.\n- When using `anytype`, add a doc comment describing the expected interface or constraints.\n\n### Examples\n\nPrefer explicit comptime type (good):\n```zig\nfn sum(comptime T: type, items: []const T) T {\n    var total: T = 0;\n    for (items) |item| {\n        total += item;\n    }\n    return total;\n}\n```\n\nAvoid anytype when type is known (bad):\n```zig\n\u002F\u002F Unclear what types are valid; error messages will be confusing\nfn sum(items: anytype) @TypeOf(items[0]) {\n    \u002F\u002F ...\n}\n```\n\nAcceptable anytype for callbacks:\n```zig\n\u002F\u002F\u002F Calls `callback` for each item. Callback must accept (T) and return void.\nfn forEach(comptime T: type, items: []const T, callback: anytype) void {\n    for (items) |item| {\n        callback(item);\n    }\n}\n```\n\nUsing @TypeOf when anytype is necessary:\n```zig\nfn debugPrint(value: anytype) void {\n    const T = @TypeOf(value);\n    if (@typeInfo(T) == .Pointer) {\n        std.debug.print(\"ptr: {*}\\n\", .{value});\n    } else {\n        std.debug.print(\"val: {}\\n\", .{value});\n    }\n}\n```\n\n## Error Handling Patterns\n\n- Define specific error sets for functions; avoid `anyerror` when possible. Specific errors document failure modes.\n- Use `catch` with a block for error recovery or logging; use `catch unreachable` only when errors are truly impossible.\n- Merge error sets with `||` when combining operations that can fail in different ways.\n\n### Examples\n\nSpecific error set:\n```zig\nconst ConfigError = error{\n    FileNotFound,\n    ParseError,\n    InvalidFormat,\n};\n\nfn loadConfig(path: []const u8) ConfigError!Config {\n    \u002F\u002F implementation\n}\n```\n\nError handling with catch block:\n```zig\nconst value = operation() catch |err| {\n    std.log.err(\"operation failed: {}\", .{err});\n    return error.OperationFailed;\n};\n```\n\n## Configuration\n\n- Load config from environment variables at startup; validate required values before use. Missing config should cause a clean exit with a descriptive message.\n- Define a Config struct as single source of truth; avoid `std.posix.getenv` scattered throughout code.\n- Use sensible defaults for development; require explicit values for production secrets.\n\n### Examples\n\nTyped config struct:\n```zig\nconst std = @import(\"std\");\n\npub const Config = struct {\n    port: u16,\n    database_url: []const u8,\n    api_key: []const u8,\n    env: []const u8,\n};\n\npub fn loadConfig() !Config {\n    const db_url = std.posix.getenv(\"DATABASE_URL\") orelse\n        return error.MissingDatabaseUrl;\n    const api_key = std.posix.getenv(\"API_KEY\") orelse\n        return error.MissingApiKey;\n    const port_str = std.posix.getenv(\"PORT\") orelse \"3000\";\n    const port = std.fmt.parseInt(u16, port_str, 10) catch\n        return error.InvalidPort;\n\n    return .{\n        .port = port,\n        .database_url = db_url,\n        .api_key = api_key,\n        .env = std.posix.getenv(\"ENV\") orelse \"development\",\n    };\n}\n```\n\n## Optionals\n\n- Use `orelse` to provide default values for optionals; use `.?` only when null is a program error.\n- Prefer `if (optional) |value|` pattern for safe unwrapping with access to the value.\n\n### Examples\n\nSafe optional handling:\n```zig\nfn findWidget(id: u32) ?*Widget {\n    \u002F\u002F lookup implementation\n}\n\nfn processWidget(id: u32) !void {\n    const widget = findWidget(id) orelse return error.WidgetNotFound;\n    try widget.process();\n}\n```\n\nOptional with if unwrapping:\n```zig\nif (maybeValue) |value| {\n    try processValue(value);\n} else {\n    std.log.warn(\"no value present\", .{});\n}\n```\n\n## Advanced Topics\n\nReference these guides for specialized patterns:\n\n- **Building custom containers** (queues, stacks, trees): See [GENERICS.md](GENERICS.md)\n- **Interfacing with C libraries** (raylib, SDL, curl, system APIs): See [C-INTEROP.md](C-INTEROP.md)\n- **Debugging memory leaks** (GPA, stack traces): See [DEBUGGING.md](DEBUGGING.md)\n\n## References\n\n- Language Reference: https:\u002F\u002Fziglang.org\u002Fdocumentation\u002F0.15.2\u002F\n- Standard Library: https:\u002F\u002Fziglang.org\u002Fdocumentation\u002F0.15.2\u002Fstd\u002F\n- Code Samples: https:\u002F\u002Fziglang.org\u002Flearn\u002Fsamples\u002F\n- Zig Guide: https:\u002F\u002Fzig.guide\u002F\n","# Zig Best Practices\n\n## Type-First Development\n\nTypes define the contract before implementation. Follow this workflow:\n\n1. **Define data structures** - structs, unions, and error sets first\n2. **Define function signatures** - parameters, return types, and error unions\n3. **Implement to satisfy types** - let the compiler guide completeness\n4. **Validate at comptime** - catch invalid configurations during compilation\n\n### Make Illegal States Unrepresentable\n\nUse Zig's type system to prevent invalid states at compile time.\n\n**Tagged unions for mutually exclusive states:**\n```zig\n\u002F\u002F Good: only valid combinations possible\nconst RequestState = union(enum) {\n    idle,\n    loading,\n    success: []const u8,\n    failure: anyerror,\n};\n\nfn handleState(state: RequestState) void {\n    switch (state) {\n        .idle => {},\n        .loading => showSpinner(),\n        .success => |data| render(data),\n        .failure => |err| showError(err),\n    }\n}\n\n\u002F\u002F Bad: allows invalid combinations\nconst RequestState = struct {\n    loading: bool,\n    data: ?[]const u8,\n    err: ?anyerror,\n};\n```\n\n**Explicit error sets for failure modes:**\n```zig\n\u002F\u002F Good: documents exactly what can fail\nconst ParseError = error{\n    InvalidSyntax,\n    UnexpectedToken,\n    EndOfInput,\n};\n\nfn parse(input: []const u8) ParseError!Ast {\n    \u002F\u002F implementation\n}\n\n\u002F\u002F Bad: anyerror hides failure modes\nfn parse(input: []const u8) anyerror!Ast {\n    \u002F\u002F implementation\n}\n```\n\n**Distinct types for domain concepts:**\n```zig\n\u002F\u002F Prevent mixing up IDs of different types\nconst UserId = enum(u64) { _ };\nconst OrderId = enum(u64) { _ };\n\nfn getUser(id: UserId) !User {\n    \u002F\u002F Compiler prevents passing OrderId here\n}\n\nfn createUserId(raw: u64) UserId {\n    return @enumFromInt(raw);\n}\n```\n\n**Comptime validation for invariants:**\n```zig\nfn Buffer(comptime size: usize) type {\n    if (size == 0) {\n        @compileError(\"buffer size must be greater than 0\");\n    }\n    if (size > 1024 * 1024) {\n        @compileError(\"buffer size exceeds 1MB limit\");\n    }\n    return struct {\n        data: [size]u8 = undefined,\n        len: usize = 0,\n    };\n}\n```\n\n**Non-exhaustive enums for extensibility:**\n```zig\n\u002F\u002F External enum that may gain variants\nconst Status = enum(u8) {\n    active = 1,\n    inactive = 2,\n    pending = 3,\n    _,\n};\n\nfn processStatus(status: Status) !void {\n    switch (status) {\n        .active => {},\n        .inactive => {},\n        .pending => {},\n        _ => return error.UnknownStatus,\n    }\n}\n```\n\n## Module Structure\n\nLarger cohesive files are idiomatic in Zig. Keep related code together: tests alongside implementation, comptime generics at file scope, public\u002Fprivate controlled by `pub`. Split only when a file handles genuinely separate concerns. The standard library demonstrates this pattern with files like `std\u002Fmem.zig` containing 2000+ lines of cohesive memory operations.\n\n## Instructions\n\n- Return errors with context using error unions (`!T`); every function returns a value or an error. Explicit error sets document failure modes.\n- Use `errdefer` for cleanup on error paths; use `defer` for unconditional cleanup. This prevents resource leaks without try-finally boilerplate.\n- Handle all branches in `switch` statements; include an `else` clause that returns an error or uses `unreachable` for truly impossible cases.\n- Pass allocators explicitly to functions requiring dynamic memory; prefer `std.testing.allocator` in tests for leak detection.\n- Prefer `const` over `var`; prefer slices over raw pointers for bounds safety. Immutability signals intent and enables optimizations.\n- Avoid `anytype`; prefer explicit `comptime T: type` parameters. Explicit types document intent and produce clearer error messages.\n- Use `std.log.scoped` for namespaced logging; define a module-level `log` constant for consistent scope across the file.\n- Add or update tests for new logic; use `std.testing.allocator` to catch memory leaks automatically.\n\n## Examples\n\nExplicit failure for unimplemented logic:\n```zig\nfn buildWidget(widget_type: []const u8) !Widget {\n    return error.NotImplemented;\n}\n```\n\nPropagate errors with try:\n```zig\nfn readConfig(path: []const u8) !Config {\n    const file = try std.fs.cwd().openFile(path, .{});\n    defer file.close();\n    const contents = try file.readToEndAlloc(allocator, max_size);\n    return parseConfig(contents);\n}\n```\n\nResource cleanup with errdefer:\n```zig\nfn createResource(allocator: std.mem.Allocator) !*Resource {\n    const resource = try allocator.create(Resource);\n    errdefer allocator.destroy(resource);\n\n    resource.* = try initializeResource();\n    return resource;\n}\n```\n\nExhaustive switch with explicit default:\n```zig\nfn processStatus(status: Status) ![]const u8 {\n    return switch (status) {\n        .active => \"processing\",\n        .inactive => \"skipped\",\n        _ => error.UnhandledStatus,\n    };\n}\n```\n\nTesting with memory leak detection:\n```zig\nconst std = @import(\"std\");\n\ntest \"widget creation\" {\n    const allocator = std.testing.allocator;\n    var list: std.ArrayListUnmanaged(u32) = .empty;\n    defer list.deinit(allocator);\n\n    try list.append(allocator, 42);\n    try std.testing.expectEqual(1, list.items.len);\n}\n```\n\n## Memory Management\n\n- Pass allocators explicitly; never use global state for allocation. Functions declare their allocation needs in parameters.\n- Use `defer` immediately after acquiring a resource. Place cleanup logic next to acquisition for clarity.\n- Prefer arena allocators for temporary allocations; they free everything at once when the arena is destroyed.\n- Use `std.testing.allocator` in tests; it reports leaks with stack traces showing allocation origins.\n\n### Examples\n\nAllocator as explicit parameter:\n```zig\nfn processData(allocator: std.mem.Allocator, input: []const u8) ![]u8 {\n    const result = try allocator.alloc(u8, input.len * 2);\n    errdefer allocator.free(result);\n\n    \u002F\u002F process input into result\n    return result;\n}\n```\n\nArena allocator for batch operations:\n```zig\nfn processBatch(items: []const Item) !void {\n    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);\n    defer arena.deinit();\n    const allocator = arena.allocator();\n\n    for (items) |item| {\n        const processed = try processItem(allocator, item);\n        try outputResult(processed);\n    }\n    \u002F\u002F All allocations freed when arena deinits\n}\n```\n\n## Logging\n\n- Use `std.log.scoped` to create namespaced loggers; each module should define its own scoped logger for filtering.\n- Define a module-level `const log` at the top of the file; use it consistently throughout the module.\n- Use appropriate log levels: `err` for failures, `warn` for suspicious conditions, `info` for state changes, `debug` for tracing.\n\n### Examples\n\nScoped logger for a module:\n```zig\nconst std = @import(\"std\");\nconst log = std.log.scoped(.widgets);\n\npub fn createWidget(name: []const u8) !Widget {\n    log.debug(\"creating widget: {s}\", .{name});\n    const widget = try allocateWidget(name);\n    log.debug(\"created widget id={d}\", .{widget.id});\n    return widget;\n}\n\npub fn deleteWidget(id: u32) void {\n    log.info(\"deleting widget id={d}\", .{id});\n    \u002F\u002F cleanup\n}\n```\n\nMultiple scopes in a codebase:\n```zig\n\u002F\u002F In src\u002Fdb.zig\nconst log = std.log.scoped(.db);\n\n\u002F\u002F In src\u002Fhttp.zig\nconst log = std.log.scoped(.http);\n\n\u002F\u002F In src\u002Fauth.zig\nconst log = std.log.scoped(.auth);\n```\n\n## Comptime Patterns\n\n- Use `comptime` parameters for generic functions; type information is available at compile time with zero runtime cost.\n- Prefer compile-time validation over runtime checks when possible. Catch errors during compilation rather than in production.\n- Use `@compileError` for invalid configurations that should fail the build.\n\n### Examples\n\nGeneric function with comptime type:\n```zig\nfn max(comptime T: type, a: T, b: T) T {\n    return if (a > b) a else b;\n}\n```\n\nCompile-time validation:\n```zig\nfn createBuffer(comptime size: usize) [size]u8 {\n    if (size == 0) {\n        @compileError(\"buffer size must be greater than 0\");\n    }\n    return [_]u8{0} ** size;\n}\n```\n\n## Avoiding anytype\n\n- Prefer `comptime T: type` over `anytype`; explicit type parameters document expected constraints and produce clearer errors.\n- Use `anytype` only when the function genuinely accepts any type (like `std.debug.print`) or for callbacks\u002Fclosures.\n- When using `anytype`, add a doc comment describing the expected interface or constraints.\n\n### Examples\n\nPrefer explicit comptime type (good):\n```zig\nfn sum(comptime T: type, items: []const T) T {\n    var total: T = 0;\n    for (items) |item| {\n        total += item;\n    }\n    return total;\n}\n```\n\nAvoid anytype when type is known (bad):\n```zig\n\u002F\u002F Unclear what types are valid; error messages will be confusing\nfn sum(items: anytype) @TypeOf(items[0]) {\n    \u002F\u002F ...\n}\n```\n\nAcceptable anytype for callbacks:\n```zig\n\u002F\u002F\u002F Calls `callback` for each item. Callback must accept (T) and return void.\nfn forEach(comptime T: type, items: []const T, callback: anytype) void {\n    for (items) |item| {\n        callback(item);\n    }\n}\n```\n\nUsing @TypeOf when anytype is necessary:\n```zig\nfn debugPrint(value: anytype) void {\n    const T = @TypeOf(value);\n    if (@typeInfo(T) == .Pointer) {\n        std.debug.print(\"ptr: {*}\\n\", .{value});\n    } else {\n        std.debug.print(\"val: {}\\n\", .{value});\n    }\n}\n```\n\n## Error Handling Patterns\n\n- Define specific error sets for functions; avoid `anyerror` when possible. Specific errors document failure modes.\n- Use `catch` with a block for error recovery or logging; use `catch unreachable` only when errors are truly impossible.\n- Merge error sets with `||` when combining operations that can fail in different ways.\n\n### Examples\n\nSpecific error set:\n```zig\nconst ConfigError = error{\n    FileNotFound,\n    ParseError,\n    InvalidFormat,\n};\n\nfn loadConfig(path: []const u8) ConfigError!Config {\n    \u002F\u002F implementation\n}\n```\n\nError handling with catch block:\n```zig\nconst value = operation() catch |err| {\n    std.log.err(\"operation failed: {}\", .{err});\n    return error.OperationFailed;\n};\n```\n\n## Configuration\n\n- Load config from environment variables at startup; validate required values before use. Missing config should cause a clean exit with a descriptive message.\n- Define a Config struct as single source of truth; avoid `std.posix.getenv` scattered throughout code.\n- Use sensible defaults for development; require explicit values for production secrets.\n\n### Examples\n\nTyped config struct:\n```zig\nconst std = @import(\"std\");\n\npub const Config = struct {\n    port: u16,\n    database_url: []const u8,\n    api_key: []const u8,\n    env: []const u8,\n};\n\npub fn loadConfig() !Config {\n    const db_url = std.posix.getenv(\"DATABASE_URL\") orelse\n        return error.MissingDatabaseUrl;\n    const api_key = std.posix.getenv(\"API_KEY\") orelse\n        return error.MissingApiKey;\n    const port_str = std.posix.getenv(\"PORT\") orelse \"3000\";\n    const port = std.fmt.parseInt(u16, port_str, 10) catch\n        return error.InvalidPort;\n\n    return .{\n        .port = port,\n        .database_url = db_url,\n        .api_key = api_key,\n        .env = std.posix.getenv(\"ENV\") orelse \"development\",\n    };\n}\n```\n\n## Optionals\n\n- Use `orelse` to provide default values for optionals; use `.?` only when null is a program error.\n- Prefer `if (optional) |value|` pattern for safe unwrapping with access to the value.\n\n### Examples\n\nSafe optional handling:\n```zig\nfn findWidget(id: u32) ?*Widget {\n    \u002F\u002F lookup implementation\n}\n\nfn processWidget(id: u32) !void {\n    const widget = findWidget(id) orelse return error.WidgetNotFound;\n    try widget.process();\n}\n```\n\nOptional with if unwrapping:\n```zig\nif (maybeValue) |value| {\n    try processValue(value);\n} else {\n    std.log.warn(\"no value present\", .{});\n}\n```\n\n## Advanced Topics\n\nReference these guides for specialized patterns:\n\n- **Building custom containers** (queues, stacks, trees): See [GENERICS.md](GENERICS.md)\n- **Interfacing with C libraries** (raylib, SDL, curl, system APIs): See [C-INTEROP.md](C-INTEROP.md)\n- **Debugging memory leaks** (GPA, stack traces): See [DEBUGGING.md](DEBUGGING.md)\n\n## References\n\n- Language Reference: https:\u002F\u002Fziglang.org\u002Fdocumentation\u002F0.15.2\u002F\n- Standard Library: https:\u002F\u002Fziglang.org\u002Fdocumentation\u002F0.15.2\u002Fstd\u002F\n- Code Samples: https:\u002F\u002Fziglang.org\u002Flearn\u002Fsamples\u002F\n- Zig Guide: https:\u002F\u002Fzig.guide\u002F\n",{"name":5,"description":7},"main","def8531e65114c0fca8fb8551c1871ee0eed705c","skills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices",24,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub","https:\u002F\u002Fskillshub.wtf","https:\u002F\u002Fgithub.com\u002FComeOnOliver","AI & Blockchain Engineer\r\n","2026-06-24 22:07:19",{"source":8,"skillName":5,"commands":49,"prompt":59,"zipAvailable":60},[50,53,56],{"tool":51,"command":52},"npx","npx skills add ComeOnOliver\u002Fskillshub --skill zig-best-practices",{"tool":54,"command":55},"bunx","bunx skills add ComeOnOliver\u002Fskillshub --skill zig-best-practices",{"tool":57,"command":58},"pnpm","pnpm dlx skills add ComeOnOliver\u002Fskillshub --skill zig-best-practices","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002FSKILL.md",true,[62,68,72,76,82,86,90,94,98,102,106,110],{"path":63,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":66,"sourceHtmlUrl":67},"backlog-template.md","REFERENCE","参考文档",564,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fbacklog-template.md",{"path":69,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":70,"sourceHtmlUrl":71},"C-INTEROP.md",2088,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002FC-INTEROP.md",{"path":73,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":74,"sourceHtmlUrl":75},"checklist.md",1116,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fchecklist.md",{"path":77,"resourceType":78,"resourceTypeDesc":79,"sizeBytes":80,"sourceHtmlUrl":81},"customize.toml","OTHER","其他",1617,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fcustomize.toml",{"path":83,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":84,"sourceHtmlUrl":85},"DEBUGGING.md",1674,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002FDEBUGGING.md",{"path":87,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":88,"sourceHtmlUrl":89},"discover-inputs.md",3911,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fdiscover-inputs.md",{"path":91,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":92,"sourceHtmlUrl":93},"GENERICS.md",1789,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002FGENERICS.md",{"path":95,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":96,"sourceHtmlUrl":97},"skill-report.json",28245,"https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Faiskillstore\u002Fmarketplace\u002F0xbigboss\u002Fzig-best-practices\u002Fskill-report.json",{"path":99,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":100,"sourceHtmlUrl":101},"steps\u002Fstep-01-gather-context.md",6518,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fsteps\u002Fstep-01-gather-context.md",{"path":103,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":104,"sourceHtmlUrl":105},"steps\u002Fstep-02-review.md",2264,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fsteps\u002Fstep-02-review.md",{"path":107,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":108,"sourceHtmlUrl":109},"steps\u002Fstep-03-triage.md",2729,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fsteps\u002Fstep-03-triage.md",{"path":111,"resourceType":64,"resourceTypeDesc":65,"sizeBytes":112,"sourceHtmlUrl":113},"steps\u002Fstep-04-present.md",6359,"https:\u002F\u002Fgithub.com\u002FdevelopAgent\u002Fbmad-start\u002Fblob\u002Fmain\u002F.rovodev\u002Fskills\u002Fgds-code-review\u002Fsteps\u002Fstep-04-present.md",[115,124,133,142,148,154],{"skillNo":116,"name":117,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":118,"categories":119,"keywords":120,"publishedAt":34},"01M6FKJN13GMG4KY57J3QD8GY5","model-hierarchy-skill","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzscole\u002Fmodel-hierarchy-skill\u002Fmodel-hierarchy-skill\u002FSKILL.md",[],[121,122,123],"model","model hierarchy","model hierarchy skill",{"skillNo":125,"name":126,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":34},"01M6FKJJJ6GCAMR4PPPRD12M5X","zoom-mcp","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-mcp\u002FSKILL.md",[],[130,131,132],"MCP","zoom","zoom mcp",{"skillNo":134,"name":135,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":136,"categories":137,"keywords":138,"publishedAt":34},"01M6FKJE3KYT3KPEZMEEHYKA6K","zoom-apps-sdk","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fzoom-apps-sdk\u002FSKILL.md",[],[139,140,141,131],"sdk","zoom apps sdk","apps",{"skillNo":143,"name":144,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":145,"categories":146,"keywords":147,"publishedAt":34},"01M6FKJ9EDH9Q5VWDF8HAJRSP0","windows","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwindows\u002FSKILL.md",[],[144],{"skillNo":149,"name":150,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":151,"categories":152,"keywords":153,"publishedAt":34},"01M6FKJ666BEEFC3AE9GJ72Q93","whiteboard","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwhiteboard\u002FSKILL.md",[],[150],{"skillNo":155,"name":156,"nameZh":6,"description":6,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":157,"categories":158,"keywords":159,"publishedAt":34},"01M6FKJ21WFCDGTJQ2Q91T9DVW","websockets","https:\u002F\u002Fgithub.com\u002FComeOnOliver\u002Fskillshub\u002Fblob\u002Fmain\u002Fskills\u002Fzoom\u002Fskills\u002Fwebsockets\u002FSKILL.md",[],[156]]