zig-expert

Compare original and translation side by side

🇺🇸

Original

English
🇨🇳

Translation

Chinese

Zig Expert Skill

Zig 专家技能

You are an expert Zig developer specializing in Zig 0.15.2. Apply these patterns, idioms, and best practices when assisting with Zig development.
你是专注于Zig 0.15.2的资深Zig开发者。在协助进行Zig开发时,请遵循以下模式、惯用写法和最佳实践。

Core Language Principles

核心语言原则

Memory Management Philosophy

内存管理理念

Zig has no hidden memory allocations. All allocations are explicit via allocators passed as parameters. This enables:
  • Testability (inject test allocators for leak detection)
  • Flexibility (swap allocators based on context)
  • Clarity (visible allocation points)
Zig 没有隐藏的内存分配。所有分配都通过作为参数传递的Allocator显式完成。这带来了以下优势:
  • 可测试性(注入测试用Allocator以检测内存泄漏)
  • 灵活性(根据上下文切换Allocator)
  • 清晰性(分配点可见)

Error Handling Philosophy

错误处理理念

Errors are values, not exceptions. Error unions (
!T
) combine a payload with an error set. Use:
  • try
    to propagate errors to caller
  • catch
    to handle errors locally
  • errdefer
    for cleanup on error paths
错误是值,而非异常。错误联合类型(
!T
)将有效载荷与错误集合结合。使用方式:
  • try
    将错误传播给调用者
  • catch
    在本地处理错误
  • errdefer
    用于错误路径上的资源清理

Comptime Philosophy

Comptime理念

Compile-time execution replaces macros and generics. The same code runs at compile-time and runtime, enabling:
  • Generic data structures via
    comptime T: type
  • Code generation via
    @typeInfo
    introspection
  • Compile-time validation and assertions

编译时执行替代了宏和泛型。同一代码可在编译时和运行时执行,实现:
  • 通过
    comptime T: type
    实现通用数据结构
  • 通过
    @typeInfo
    类型自省实现代码生成
  • 编译时验证与断言

Allocator Selection Guide

Allocator选择指南

AllocatorUse CaseThread-Safe
std.heap.GeneralPurposeAllocator
Development/debugging, leak detectionConfigurable
std.heap.ArenaAllocator
Batch operations, bulk deallocationNo
std.heap.FixedBufferAllocator
Stack-backed, embedded, no heapNo
std.heap.page_allocator
Simple backing allocatorYes
std.heap.c_allocator
Performance-critical (requires libc)Yes
std.testing.allocator
Unit tests (auto leak detection)No
Allocator适用场景线程安全
std.heap.GeneralPurposeAllocator
开发/调试、内存泄漏检测可配置
std.heap.ArenaAllocator
批量操作、批量释放
std.heap.FixedBufferAllocator
栈内存支持、嵌入式场景、无堆内存使用
std.heap.page_allocator
简单底层Allocator
std.heap.c_allocator
性能敏感场景(依赖libc)
std.testing.allocator
单元测试(自动检测内存泄漏)

Standard Allocator Patterns

标准Allocator使用模式

Application Entry Point:
zig
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        const status = gpa.deinit();
        if (status == .leak) @panic("Memory leak detected!");
    }
    const allocator = gpa.allocator();

    try run(allocator);
}
Arena for Batch Operations:
zig
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit(); // Frees ALL allocations at once
const allocator = arena.allocator();

// No individual frees needed
_ = try allocator.alloc(u8, 100);
_ = try allocator.alloc(u8, 200);
Testing with Leak Detection:
zig
test "memory safety" {
    var list = std.ArrayList(i32).init(std.testing.allocator);
    defer list.deinit();
    try list.append(42);
    try std.testing.expectEqual(@as(i32, 42), list.pop());
}

应用入口点:
zig
pub fn main() !void {
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer {
        const status = gpa.deinit();
        if (status == .leak) @panic("Memory leak detected!");
    }
    const allocator = gpa.allocator();

    try run(allocator);
}
批量操作使用Arena:
zig
var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
defer arena.deinit(); // 一次性释放所有分配的内存
const allocator = arena.allocator();

// 无需单独释放每个分配
_ = try allocator.alloc(u8, 100);
_ = try allocator.alloc(u8, 200);
带内存泄漏检测的测试:
zig
test "memory safety" {
    var list = std.ArrayList(i32).init(std.testing.allocator);
    defer list.deinit();
    try list.append(42);
    try std.testing.expectEqual(@as(i32, 42), list.pop());
}

Error Handling Patterns

错误处理模式

Error Union Basics

错误联合类型基础

zig
// Define specific error sets (preferred over anyerror)
const FileError = error{
    AccessDenied,
    FileNotFound,
    OutOfMemory,
};

// Inferred error set (use sparingly)
fn process() !void {
    // Error set inferred from all possible errors
}
zig
// 定义特定的错误集合(优先于anyerror)
const FileError = error{
    AccessDenied,
    FileNotFound,
    OutOfMemory,
};

// 推断的错误集合(谨慎使用)
fn process() !void {
    // 错误集合由所有可能的错误自动推断
}

try/catch/orelse Idioms

try/catch/orelse 惯用写法

zig
// try: Propagate error to caller
const file = try std.fs.cwd().openFile("data.txt", .{});

// catch: Handle error locally
const value = getValue() catch |err| switch (err) {
    error.OutOfMemory => return error.OutOfMemory,
    error.FileNotFound => return default_value,
    else => unreachable,
};

// catch with default
const result = mayFail() catch default;

// orelse: For optionals
const unwrapped = optional_value orelse default_value;
zig
// try: 将错误传播给调用者
const file = try std.fs.cwd().openFile("data.txt", .{});

// catch: 在本地处理错误
const value = getValue() catch |err| switch (err) {
    error.OutOfMemory => return error.OutOfMemory,
    error.FileNotFound => return default_value,
    else => unreachable,
};

// catch 搭配默认值
const result = mayFail() catch default;

// orelse: 用于可选类型
const unwrapped = optional_value orelse default_value;

errdefer for Resource Cleanup (Critical Pattern)

用于资源清理的errdefer(关键模式)

zig
fn initResource(allocator: Allocator) !*Resource {
    const resource = try allocator.create(Resource);
    errdefer allocator.destroy(resource); // Runs ONLY if error returned

    resource.buffer = try allocator.alloc(u8, 1024);
    errdefer allocator.free(resource.buffer);

    try resource.initialize(); // If this fails, both errdefers run
    return resource;
}
zig
fn initResource(allocator: Allocator) !*Resource {
    const resource = try allocator.create(Resource);
    errdefer allocator.destroy(resource); // 仅在返回错误时执行

    resource.buffer = try allocator.alloc(u8, 1024);
    errdefer allocator.free(resource.buffer);

    try resource.initialize(); // 如果此步骤失败,两个errdefer都会执行
    return resource;
}

defer/errdefer Execution Order

defer/errdefer 执行顺序

zig
fn example() !void {
    const a = try allocate();
    defer free(a);           // Runs: 3rd (last defer, first to run)
    errdefer cleanup(a);     // Runs: only on error, before defers

    const b = try allocate();
    defer free(b);           // Runs: 2nd

    const c = try allocate();
    defer free(c);           // Runs: 1st

    // Normal exit: free(c), free(b), free(a)
    // Error exit: cleanup(a), then error propagates
}

zig
fn example() !void {
    const a = try allocate();
    defer free(a);           // 执行顺序:第3位(最后声明的defer,最先执行)
    errdefer cleanup(a);     // 仅在出错时执行,早于所有defer

    const b = try allocate();
    defer free(b);           // 执行顺序:第2位

    const c = try allocate();
    defer free(c);           // 执行顺序:第1位

    // 正常退出:free(c), free(b), free(a)
    // 出错退出:cleanup(a),然后错误向上传播
}

Comptime and Generics Patterns

Comptime与泛型模式

Generic Data Structure Template

通用数据结构模板

zig
pub fn ArrayList(comptime T: type) type {
    return struct {
        items: []T,
        capacity: usize,
        allocator: std.mem.Allocator,

        const Self = @This();

        pub fn init(allocator: std.mem.Allocator) Self {
            return .{ .items = &.{}, .capacity = 0, .allocator = allocator };
        }

        pub fn deinit(self: *Self) void {
            if (self.capacity > 0) {
                self.allocator.free(self.items.ptr[0..self.capacity]);
            }
        }

        pub fn append(self: *Self, item: T) !void {
            if (self.items.len >= self.capacity) {
                try self.ensureCapacity(self.capacity * 2 + 1);
            }
            self.items.len += 1;
            self.items[self.items.len - 1] = item;
        }
    };
}
zig
pub fn ArrayList(comptime T: type) type {
    return struct {
        items: []T,
        capacity: usize,
        allocator: std.mem.Allocator,

        const Self = @This();

        pub fn init(allocator: std.mem.Allocator) Self {
            return .{ .items = &.{}, .capacity = 0, .allocator = allocator };
        }

        pub fn deinit(self: *Self) void {
            if (self.capacity > 0) {
                self.allocator.free(self.items.ptr[0..self.capacity]);
            }
        }

        pub fn append(self: *Self, item: T) !void {
            if (self.items.len >= self.capacity) {
                try self.ensureCapacity(self.capacity * 2 + 1);
            }
            self.items.len += 1;
            self.items[self.items.len - 1] = item;
        }
    };
}

Type Introspection Pattern

类型自省模式

zig
fn serialize(comptime T: type, value: T) ![]u8 {
    const info = @typeInfo(T);
    return switch (info) {
        .@"struct" => |s| {
            inline for (s.fields) |field| {
                const field_value = @field(value, field.name);
                // Process each field...
            }
        },
        .int => std.fmt.allocPrint(allocator, "{d}", .{value}),
        .float => std.fmt.allocPrint(allocator, "{d}", .{value}),
        else => @compileError("Unsupported type: " ++ @typeName(T)),
    };
}
zig
fn serialize(comptime T: type, value: T) ![]u8 {
    const info = @typeInfo(T);
    return switch (info) {
        .@"struct" => |s| {
            inline for (s.fields) |field| {
                const field_value = @field(value, field.name);
                // 处理每个字段...
            }
        },
        .int => std.fmt.allocPrint(allocator, "{d}", .{value}),
        .float => std.fmt.allocPrint(allocator, "{d}", .{value}),
        else => @compileError("Unsupported type: " ++ @typeName(T)),
    };
}

Compile-Time Validation

编译时验证

zig
fn Vector(comptime size: usize) type {
    if (size == 0) @compileError("Vector size must be > 0");
    if (size > 1024) @compileError("Vector size too large");

    return struct {
        data: [size]f32,

        pub fn dot(self: @This(), other: @This()) f32 {
            var sum: f32 = 0;
            inline for (0..size) |i| {
                sum += self.data[i] * other.data[i];
            }
            return sum;
        }
    };
}
zig
fn Vector(comptime size: usize) type {
    if (size == 0) @compileError("Vector size must be > 0");
    if (size > 1024) @compileError("Vector size too large");

    return struct {
        data: [size]f32,

        pub fn dot(self: @This(), other: @This()) f32 {
            var sum: f32 = 0;
            inline for (0..size) |i| {
                sum += self.data[i] * other.data[i];
            }
            return sum;
        }
    };
}

anytype Duck Typing

anytype 鸭子类型

zig
fn print(writer: anytype, value: anytype) !void {
    const T = @TypeOf(value);
    if (@hasDecl(T, "format")) {
        try value.format(writer);
    } else {
        try writer.print("{any}", .{value});
    }
}

zig
fn print(writer: anytype, value: anytype) !void {
    const T = @TypeOf(value);
    if (@hasDecl(T, "format")) {
        try value.format(writer);
    } else {
        try writer.print("{any}", .{value});
    }
}

Type System Patterns

类型系统模式

Tagged Union (Sum Type) Pattern

标记联合(和类型)模式

zig
const JsonValue = union(enum) {
    null,
    bool: bool,
    number: f64,
    string: []const u8,
    array: []JsonValue,
    object: std.StringHashMap(JsonValue),

    pub fn isNull(self: JsonValue) bool {
        return self == .null;
    }
};

// Pattern matching with payload capture
fn processJson(value: JsonValue) void {
    switch (value) {
        .null => {},
        .bool => |b| std.debug.print("bool: {}\n", .{b}),
        .number => |n| std.debug.print("number: {d}\n", .{n}),
        .string => |s| std.debug.print("string: {s}\n", .{s}),
        .array => |arr| for (arr) |item| processJson(item),
        .object => |obj| {
            var it = obj.iterator();
            while (it.next()) |entry| {
                std.debug.print("{s}: ", .{entry.key_ptr.*});
                processJson(entry.value_ptr.*);
            }
        },
    }
}
zig
const JsonValue = union(enum) {
    null,
    bool: bool,
    number: f64,
    string: []const u8,
    array: []JsonValue,
    object: std.StringHashMap(JsonValue),

    pub fn isNull(self: JsonValue) bool {
        return self == .null;
    }
};

// 带载荷捕获的模式匹配
fn processJson(value: JsonValue) void {
    switch (value) {
        .null => {},
        .bool => |b| std.debug.print("bool: {}\n", .{b}),
        .number => |n| std.debug.print("number: {d}\n", .{n}),
        .string => |s| std.debug.print("string: {s}\n", .{s}),
        .array => |arr| for (arr) |item| processJson(item),
        .object => |obj| {
            var it = obj.iterator();
            while (it.next()) |entry| {
                std.debug.print("{s}: ", .{entry.key_ptr.*});
                processJson(entry.value_ptr.*);
            }
        },
    }
}

Packed Struct for Bit Fields

用于位字段的Packed Struct

zig
const Flags = packed struct(u8) {
    enabled: bool,      // bit 0
    priority: u3,       // bits 1-3
    mode: enum(u2) { normal, fast, slow, custom }, // bits 4-5
    reserved: u2 = 0,   // bits 6-7
};

// Bitcast to/from backing integer
const flags = Flags{ .enabled = true, .priority = 5, .mode = .fast };
const byte: u8 = @bitCast(flags);
const restored: Flags = @bitCast(byte);
zig
const Flags = packed struct(u8) {
    enabled: bool,      // 第0位
    priority: u3,       // 第1-3位
    mode: enum(u2) { normal, fast, slow, custom }, // 第4-5位
    reserved: u2 = 0,   // 第6-7位
};

// 与底层整数之间的位转换
const flags = Flags{ .enabled = true, .priority = 5, .mode = .fast };
const byte: u8 = @bitCast(flags);
const restored: Flags = @bitCast(byte);

extern struct for C Interop

用于C语言互操作的extern struct

zig
const CStruct = extern struct {
    x: c_int,
    y: c_long,
    data: [256]u8,
};

// Guaranteed C-compatible layout
comptime {
    std.debug.assert(@sizeOf(CStruct) == @sizeOf(c_int) + @sizeOf(c_long) + 256);
}

zig
const CStruct = extern struct {
    x: c_int,
    y: c_long,
    data: [256]u8,
};

// 保证与C语言兼容的内存布局
comptime {
    std.debug.assert(@sizeOf(CStruct) == @sizeOf(c_int) + @sizeOf(c_long) + 256);
}

Build System Patterns

构建系统模式

Standard Executable build.zig

标准可执行文件build.zig

zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "myapp",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    b.installArtifact(exe);

    // Run step
    const run_exe = b.addRunArtifact(exe);
    run_exe.step.dependOn(b.getInstallStep());
    if (b.args) |args| run_exe.addArgs(args);

    const run_step = b.step("run", "Run the application");
    run_step.dependOn(&run_exe.step);

    // Test step
    const unit_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    const run_tests = b.addRunArtifact(unit_tests);
    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_tests.step);
}
zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const exe = b.addExecutable(.{
        .name = "myapp",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    b.installArtifact(exe);

    // 运行步骤
    const run_exe = b.addRunArtifact(exe);
    run_exe.step.dependOn(b.getInstallStep());
    if (b.args) |args| run_exe.addArgs(args);

    const run_step = b.step("run", "Run the application");
    run_step.dependOn(&run_exe.step);

    // 测试步骤
    const unit_tests = b.addTest(.{
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/main.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });
    const run_tests = b.addRunArtifact(unit_tests);
    const test_step = b.step("test", "Run unit tests");
    test_step.dependOn(&run_tests.step);
}

Library with C Integration

集成C语言的库

zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const lib = b.addStaticLibrary(.{
        .name = "mylib",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/lib.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    // Link system libraries
    lib.linkSystemLibrary("z");
    lib.linkLibC();

    // Add C source files
    lib.addCSourceFiles(.{
        .files = &.{ "src/c/helper.c" },
        .flags = &.{ "-std=c99", "-O2" },
    });

    lib.addIncludePath(b.path("include/"));
    b.installArtifact(lib);
}
zig
const std = @import("std");

pub fn build(b: *std.Build) void {
    const target = b.standardTargetOptions(.{});
    const optimize = b.standardOptimizeOption(.{});

    const lib = b.addStaticLibrary(.{
        .name = "mylib",
        .root_module = b.createModule(.{
            .root_source_file = b.path("src/lib.zig"),
            .target = target,
            .optimize = optimize,
        }),
    });

    // 链接系统库
    lib.linkSystemLibrary("z");
    lib.linkLibC();

    // 添加C语言源文件
    lib.addCSourceFiles(.{
        .files = &.{ "src/c/helper.c" },
        .flags = &.{ "-std=c99", "-O2" },
    });

    lib.addIncludePath(b.path("include/"));
    b.installArtifact(lib);
}

build.zig.zon Dependencies

build.zig.zon 依赖配置

zig
.{
    .name = "my_project",
    .version = "0.1.0",
    .dependencies = .{
        .zap = .{
            .url = "https://github.com/zigzap/zap/archive/refs/tags/v0.1.7.tar.gz",
            .hash = "1220002d24d73672fe8b1e39717c0671598acc8ec27b8af2e1caf623a4fd0ce0d1bd",
        },
        .local_lib = .{
            .path = "../lib",
        },
    },
    .paths = .{ "build.zig", "build.zig.zon", "src" },
}

zig
.{
    .name = "my_project",
    .version = "0.1.0",
    .dependencies = .{
        .zap = .{
            .url = "https://github.com/zigzap/zap/archive/refs/tags/v0.1.7.tar.gz",
            .hash = "1220002d24d73672fe8b1e39717c0671598acc8ec27b8af2e1caf623a4fd0ce0d1bd",
        },
        .local_lib = .{
            .path = "../lib",
        },
    },
    .paths = .{ "build.zig", "build.zig.zon", "src" },
}

Cross-Compilation

交叉编译

Command Line

命令行方式

bash
zig build -Dtarget=x86_64-linux-gnu -Doptimize=ReleaseFast
zig build -Dtarget=aarch64-macos
zig build -Dtarget=x86_64-windows-gnu
zig build -Dtarget=wasm32-freestanding
bash
zig build -Dtarget=x86_64-linux-gnu -Doptimize=ReleaseFast
zig build -Dtarget=aarch64-macos
zig build -Dtarget=x86_64-windows-gnu
zig build -Dtarget=wasm32-freestanding

Multi-Target Build

多目标构建

zig
const targets = [_]std.Target.Query{
    .{}, // native
    .{ .cpu_arch = .x86_64, .os_tag = .linux },
    .{ .cpu_arch = .x86_64, .os_tag = .windows },
    .{ .cpu_arch = .aarch64, .os_tag = .macos },
    .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
};

pub fn build(b: *std.Build) void {
    for (targets) |t| {
        const exe = b.addExecutable(.{
            .name = "myapp",
            .root_module = b.createModule(.{
                .root_source_file = b.path("src/main.zig"),
                .target = b.resolveTargetQuery(t),
                .optimize = .ReleaseFast,
            }),
        });
        b.installArtifact(exe);
    }
}

zig
const targets = [_]std.Target.Query{
    .{}, // 原生平台
    .{ .cpu_arch = .x86_64, .os_tag = .linux },
    .{ .cpu_arch = .x86_64, .os_tag = .windows },
    .{ .cpu_arch = .aarch64, .os_tag = .macos },
    .{ .cpu_arch = .wasm32, .os_tag = .freestanding },
};

pub fn build(b: *std.Build) void {
    for (targets) |t| {
        const exe = b.addExecutable(.{
            .name = "myapp",
            .root_module = b.createModule(.{
                .root_source_file = b.path("src/main.zig"),
                .target = b.resolveTargetQuery(t),
                .optimize = .ReleaseFast,
            }),
        });
        b.installArtifact(exe);
    }
}

Testing Patterns

测试模式

Test Structure

测试结构

zig
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;

test "basic functionality" {
    var list = std.ArrayList(i32).init(std.testing.allocator);
    defer list.deinit();

    try list.append(42);
    try expectEqual(@as(i32, 42), list.pop());
}

test "error handling" {
    const result = mayFail();
    try expectError(error.SomeError, result);
}

test "floating point comparison" {
    const value = calculatePi();
    try expect(@abs(value - 3.14159) < 0.00001);
}
zig
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
const expectError = std.testing.expectError;

test "basic functionality" {
    var list = std.ArrayList(i32).init(std.testing.allocator);
    defer list.deinit();

    try list.append(42);
    try expectEqual(@as(i32, 42), list.pop());
}

test "error handling" {
    const result = mayFail();
    try expectError(error.SomeError, result);
}

test "floating point comparison" {
    const value = calculatePi();
    try expect(@abs(value - 3.14159) < 0.00001);
}

Running Tests

运行测试

bash
zig build test --summary all
zig test src/main.zig

bash
zig build test --summary all
zig test src/main.zig

Common Standard Library Modules

常用标准库模块

ModulePurpose
std.mem
Memory utilities, slices, allocator interface
std.heap
Allocator implementations
std.fs
File system operations
std.net
Networking (TCP/UDP, DNS)
std.json
JSON parsing/serialization
std.fmt
String formatting
std.io
I/O readers and writers
std.ArrayList
Dynamic arrays
std.HashMap
Hash maps
std.Thread
Threading primitives
std.testing
Unit testing utilities
std.debug
Debug printing, assertions
std.log
Structured logging
std.crypto
Cryptographic primitives
std.process
Process management

模块用途
std.mem
内存工具、切片、Allocator接口
std.heap
Allocator实现
std.fs
文件系统操作
std.net
网络功能(TCP/UDP、DNS)
std.json
JSON解析/序列化
std.fmt
字符串格式化
std.io
I/O读取器和写入器
std.ArrayList
动态数组
std.HashMap
哈希表
std.Thread
线程原语
std.testing
单元测试工具
std.debug
调试打印、断言
std.log
结构化日志
std.crypto
加密原语
std.process
进程管理

Style Conventions

风格约定

ItemConventionExample
TypesPascalCase
HttpClient
,
ArrayList
FunctionscamelCase
getValue
,
processData
Constantssnake_case
max_size
,
default_port
Filessnake_case.zig
http_client.zig
Test namesDescriptive strings
"handles empty input"

约定示例
类型PascalCase
HttpClient
,
ArrayList
函数camelCase
getValue
,
processData
常量snake_case
max_size
,
default_port
文件snake_case.zig
http_client.zig
测试名称描述性字符串
"handles empty input"

Common Pitfalls to Avoid

需避免的常见陷阱

  1. Forgetting defer for cleanup: Always pair
    alloc
    with
    defer free
  2. Using anyerror: Define specific error sets for better error handling
  3. Ignoring error unions:
    _ = mayFail();
    is compile error; use
    _ = mayFail() catch {};
  4. Missing errdefer: When function can fail after allocation, use
    errdefer
  5. Expecting comptime side effects: Comptime code cannot have runtime effects
  6. Integer overflow in Release: Use
    +%
    (wrapping) or
    +|
    (saturating) when intended
  7. Forgetting sentinel for C strings: Use
    [*:0]const u8
    for null-terminated strings

  1. 忘记用defer做清理:始终将
    alloc
    defer free
    配对使用
  2. 使用anyerror:定义特定的错误集合以实现更优的错误处理
  3. 忽略错误联合类型
    _ = mayFail();
    会触发编译错误;应使用
    _ = mayFail() catch {};
  4. 遗漏errdefer:当函数在分配资源后可能失败时,务必使用
    errdefer
  5. 期望comptime产生运行时副作用:编译时代码无法产生运行时效果
  6. Release模式下的整数溢出:若预期溢出,使用
    +%
    (环绕溢出)或
    +|
    (饱和溢出)
  7. 忘记C字符串的结束符:对以null结尾的字符串使用
    [*:0]const u8
    类型

When This Skill Activates

本技能的激活场景

This skill automatically activates when:
  • Working with
    .zig
    files
  • Creating or modifying
    build.zig
    or
    build.zig.zon
  • Discussing Zig memory management, error handling, or comptime
  • Cross-compiling Zig projects
  • Integrating C code with Zig
  • Writing or debugging Zig tests
当出现以下情况时,本技能会自动激活:
  • 处理
    .zig
    文件时
  • 创建或修改
    build.zig
    build.zig.zon
  • 讨论Zig内存管理、错误处理或comptime时
  • 进行Zig项目交叉编译时
  • 将C代码与Zig集成时
  • 编写或调试Zig测试时