mcpField
Z
zig-project

zig-project

github.com/majiayu000开发28878 次安装今天更新
代码仓库

关于 zig-project

面向 Zig 项目开发的技能指南,强调显式内存管理、错误处理和编译期编程,并提供项目结构、测试与构建参考。

主要功能

  1. 01显式分配器传递
  2. 02错误联合与资源清理
  3. 03使用 comptime 编写泛型
  4. 04项目结构与构建配置
  5. 05测试和常用命令参考

适用场景

  1. 01创建 Zig 可执行程序或库
  2. 02为分配操作设计内存管理
  3. 03实现错误处理与清理逻辑
  4. 04运行项目测试和构建

安装

复制下面的命令,在终端中运行。

$npx skills add https://github.com/majiayu000/spellbook --skill zig-project

安装后在 Claude Code 中输入/zig-project确认已加载。

包含的文件

除 SKILL.md 外,安装时一起下载的参考资料和脚本。

reference/
architecture.md
extended.md
patterns.md
tech-stack.md
templates/executable/
build.zig
build.zig.zon
templates/executable/src/
lib.zig
main.zig

详细介绍

Zig 项目架构

核心原则

  • 没有隐藏行为 — 不进行隐藏分配,不存在隐藏控制流,不使用宏
  • 显式分配器 — 将分配器作为参数传递,绝不使用全局分配器
  • 使用 comptime 而非宏 — 使用 comptime 实现泛型和元编程
  • 错误联合 — 使用 !T 显式处理错误,避免使用 anyerror
  • defer/errdefer — 在作用域退出时清理资源
  • 不保证向后兼容 — 删除,不要弃用。直接修改
  • 使用 LiteLLM 调用大模型 API — 对所有大模型集成使用 LiteLLM 代理

不保证向后兼容

删除未使用的代码。直接修改。不添加兼容层。

// ❌ BAD: Deprecated function kept around
/// Deprecated: Use newFunction instead
pub fn oldFunction() void {
    @compileLog("oldFunction is deprecated");
    newFunction();
}

// ❌ BAD: Alias for renamed functions
pub const old_name = new_name; // "for backwards compatibility"

// ❌ BAD: Unused parameters
fn process(_: *const Config, data: []const u8) !void {
    _ = data;
}

// ✅ GOOD: Just delete and update all usages
pub fn newFunction() void {
    // ...
}

// ✅ GOOD: Remove unused parameters entirely
fn process(data: []const u8) !void {
    // ...
}

使用 LiteLLM 调用大模型 API

使用 LiteLLM 代理。不要直接调用提供商 API。

const std = @import("std");
const http = std.http;

pub const LLMClient = struct {
    allocator: std.mem.Allocator,
    base_url: []const u8,
    api_key: []const u8,

    pub fn init(allocator: std.mem.Allocator, base_url: []const u8, api_key: []const u8) LLMClient {
        return .{
            .allocator = allocator,
            .base_url = base_url,  // "http://localhost:4000"
            .api_key = api_key,
        };
    }

    pub fn complete(self: *LLMClient, prompt: []const u8, model: []const u8) ![]u8 {
        // Use OpenAI-compatible API through LiteLLM proxy
        var client = http.Client{ .allocator = self.allocator };
        defer client.deinit();

        // Build request to LiteLLM proxy...
        _ = prompt;
        _ = model;
        return "";
    }
};

快速入门

1. 初始化项目
# Create new project
mkdir myapp && cd myapp
zig init

# Or create executable project
zig init-exe

# Or create library project
zig init-lib
2. 项目结构
myapp/
├── build.zig           # Build configuration (in Zig)
├── build.zig.zon       # Package manifest (dependencies)
├── src/
│   ├── main.zig        # Entry point (for exe)
│   ├── root.zig        # Library root (for lib)
│   └── lib/            # Internal modules
│       └── utils.zig
├── tests/              # Integration tests (optional)
└── lib/                # Vendored dependencies
3. 核心文件

build.zig.zon(包清单)

.{
    .name = "myapp",
    .version = "0.1.0",
    .dependencies = .{
        // .some_dep = .{
        //     .url = "https://github.com/...",
        //     .hash = "...",
        // },
    },
    .paths = .{
        "build.zig",
        "build.zig.zon",
        "src",
    },
}

build.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_source_file = b.path("src/main.zig"),
        .target = target,
        .optimize = optimize,
    });

    b.installArtifact(exe);

    // Run step
    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());
    const run_step = b.step("run", "Run the application");
    run_step.dependOn(&run_cmd.step);

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

显式分配器模式

核心原则

每个执行分配的函数都必须接收一个分配器参数。

const std = @import("std");

// ❌ BAD: Hidden allocation (don't do this)
var global_allocator: std.mem.Allocator = undefined;
fn badAlloc() ![]u8 {
    return global_allocator.alloc(u8, 100);
}

// ✅ GOOD: Explicit allocator
fn goodAlloc(allocator: std.mem.Allocator) ![]u8 {
    return allocator.alloc(u8, 100);
}
常见分配器
const std = @import("std");

pub fn main() !void {
    // General purpose (with safety checks in debug)
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // Arena (bulk alloc/dealloc)
    var arena = std.heap.ArenaAllocator.init(std.heap.page_allocator);
    defer arena.deinit();
    const arena_alloc = arena.allocator();

    // Fixed buffer (no heap)
    var buffer: [1024]u8 = undefined;
    var fba = std.heap.FixedBufferAllocator.init(&buffer);
    const fixed_alloc = fba.allocator();

    // Page allocator (direct OS calls)
    const page_alloc = std.heap.page_allocator;

    _ = allocator;
    _ = arena_alloc;
    _ = fixed_alloc;
    _ = page_alloc;
}
Arena 模式(请求作用域)
fn handleRequest(permanent_allocator: std.mem.Allocator) !void {
    // Create arena for this request
    var arena = std.heap.ArenaAllocator.init(permanent_allocator);
    defer arena.deinit();  // Free ALL request memory at once

    const allocator = arena.allocator();

    // All allocations use arena - no individual frees needed
    const data = try fetchData(allocator);
    const processed = try processData(allocator, data);
    try sendResponse(processed);

    // arena.deinit() frees everything
}

错误处理

错误联合
const std = @import("std");

// Define specific error set
const FileError = error{
    NotFound,
    AccessDenied,
    OutOfMemory,
    EndOfStream,
};

// Return error union
fn readFile(allocator: std.mem.Allocator, path: []const u8) FileError![]u8 {
    const file = std.fs.cwd().openFile(path, .{}) catch |err| {
        return switch (err) {
            error.FileNotFound => FileError.NotFound,
            error.AccessDenied => FileError.AccessDenied,
            else => FileError.NotFound,
        };
    };
    defer file.close();

    return file.readToEndAlloc(allocator, 1024 * 1024) catch FileError.OutOfMemory;
}
try / catch / errdefer
fn processFile(allocator: std.mem.Allocator, path: []const u8) !void {
    // try: propagate error up
    const data = try readFile(allocator, path);
    errdefer allocator.free(data);  // cleanup on error

    // catch: handle error locally
    const parsed = parseData(data) catch |err| {
        std.log.err("Parse failed: {}", .{err});
        return err;
    };

    try saveResult(parsed);
}
错误格式化
fn example() !void {
    doSomething() catch |err| {
        std.log.err("Operation failed: {s}", .{@errorName(err)});
        return err;
    };
}

Comptime(编译时执行)

泛型函数
fn max(comptime T: type, a: T, b: T) T {
    return if (a > b) a else b;
}

// Usage
const result = max(i32, 10, 20);  // Returns 20
const float_result = max(f64, 1.5, 2.5);  // Returns 2.5
泛型数据结构
pub fn ArrayList(comptime T: type) type {
    return struct {
        const Self = @This();

        items: []T,
        capacity: usize,
        allocator: std.mem.Allocator,

        pub fn init(allocator: std.mem.Allocator) Self {
            return .{
                .items = &[_]T{},
                .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 {
            // Implementation...
            _ = item;
        }
    };
}

// Usage
var list = ArrayList(u32).init(allocator);
defer list.deinit();
编译时验证
fn validateConfig(comptime config: Config) void {
    if (config.buffer_size == 0) {
        @compileError("buffer_size must be > 0");
    }
    if (config.buffer_size > 1024 * 1024) {
        @compileError("buffer_size too large");
    }
}

测试

内联测试
const std = @import("std");
const testing = std.testing;

fn add(a: i32, b: i32) i32 {
    return a + b;
}

test "add positive numbers" {
    try testing.expectEqual(@as(i32, 5), add(2, 3));
}

test "add negative numbers" {
    try testing.expectEqual(@as(i32, -1), add(1, -2));
}
使用分配器进行测试
test "allocation test" {
    // Use testing allocator for leak detection
    const allocator = testing.allocator;

    const data = try allocator.alloc(u8, 100);
    defer allocator.free(data);

    try testing.expect(data.len == 100);
}
测试错误
test "expect error" {
    const result = failingFunction();
    try testing.expectError(error.SomeError, result);
}

test "expect no error" {
    const result = try successFunction();
    try testing.expect(result > 0);
}
运行测试
# Run all tests
zig build test

# Run tests with output
zig test src/main.zig

# Run specific test
zig test src/main.zig --test-filter "add positive"

常用命令

# Build
zig build                    # Debug build
zig build -Doptimize=ReleaseFast  # Release build

# Run
zig build run               # Build and run

# Test
zig build test              # Run tests

# Format
zig fmt src/                # Format code

# Cross-compile
zig build -Dtarget=x86_64-linux-gnu
zig build -Dtarget=aarch64-macos
zig build -Dtarget=x86_64-windows

# Use as C compiler
zig cc -o output input.c
zig c++ -o output input.cpp

扩展参考

为保持本指南简洁,从 ## Checklist 开始的详细内容已移至 reference/extended.md。当任务需要其中移动过去的示例、命令目录、检查清单、平台详情或实现模板时,请加载该参考文档。

评论

支持 Markdown