返回主页 学习路径
Zig
无宏 · 无GC · 编译期计算
Zig 是由 Andrew Kelley 于 2016 年创建的系统级编程语言,旨在成为 C 语言的现代替代品。Zig 没有宏、没有预处理器、没有垃圾回收,但提供了编译期计算、跨平台编译、与 C 无缝互操作等强大特性。Zig 的设计哲学是"没有隐藏控制流,没有隐藏内存分配",让程序员完全掌控程序的每个细节。Zig 被 Bun 等知名项目采用,正逐渐受到系统编程社区的关注。
系统语言新锐 · C 的现代替代
📅 诞生时间2016年 · Andrew Kelley
🧩 类型系统编程 · 编译期计算
📊 类型系统静态 · 强类型
⚡性能
9/10
📦生态
3/10
🧠易用
5/10
🚀扩展性
7/10

📑 本文目录

📌 第一部分:Zig 概览与定位

1.1 定义与全称

Zig 是由 Andrew Kelley 于 2016 年创建的系统级编程语言,旨在成为 C 语言的现代替代品。Zig 的设计哲学是 "没有隐藏控制流,没有隐藏内存分配",让程序员完全掌控程序的每个细节。

1.2 核心定位

Zig 的核心定位是 现代系统编程语言。它提供了:

1.3 主要应用领域

1.4 知名案例


⚙️ 第二部分:核心语法与特性

2.1 基础语法

// 注释

// 导入标准库
const std = @import("std");

// 主函数
pub fn main() !void {
    // 打印
    std.debug.print("Hello, {s}!\n", .{"Zig"});

    // 变量(不可变)
    const name = "Zig";
    const age = 10;

    // 变量(可变)
    var count: u32 = 0;
    count += 1;

    // 数组
    const numbers = [_]i32{1, 2, 3, 4, 5};

    // 切片
    const slice = numbers[0..3];

    // 结构体
    const Person = struct {
        name: []const u8,
        age: u32,
    };

    const person = Person{
        .name = "Alice",
        .age = 30,
    };

    // 条件判断
    if (age >= 18) {
        std.debug.print("Adult\n", .{});
    } else {
        std.debug.print("Minor\n", .{});
    }

    // 循环
    for (numbers) |n| {
        std.debug.print("{}\n", .{n});
    }

    var i: u32 = 0;
    while (i < 5) : (i += 1) {
        std.debug.print("{}\n", .{i});
    }
}

2.2 编译期计算(comptime)

// 编译期执行
const std = @import("std");

// 编译期函数(在编译时执行)
fn fibonacci(comptime n: u32) u32 {
    return if (n <= 1) n else fibonacci(n - 1) + fibonacci(n - 2);
}

// 编译期常量
const FIB_10 = comptime fibonacci(10);

// 编译期断言
comptime {
    // 编译期检查
    const result = fibonacci(10);
    if (result != 55) {
        @compileError("Fibonacci calculation failed");
    }
}

// 编译期生成代码
fn makeStruct(comptime fields: []const struct { name: []const u8, type: type }) type {
    var struct_fields: []const std.builtin.Type.StructField = undefined;
    // 在编译期构建结构体
    return struct {};
}

// 编译期反射
fn printTypeInfo(comptime T: type) void {
    const info = @typeInfo(T);
    std.debug.print("Type: {s}\n", .{@typeName(T)});
}

2.3 内存管理

// 分配器(手动管理)
const std = @import("std");

pub fn main() !void {
    // 获取分配器
    var gpa = std.heap.GeneralPurposeAllocator(.{}){};
    defer _ = gpa.deinit();
    const allocator = gpa.allocator();

    // 分配内存
    const ptr = try allocator.create(i32);
    ptr.* = 42;

    // 释放内存
    allocator.destroy(ptr);

    // 分配数组
    const slice = try allocator.alloc(u8, 100);
    defer allocator.free(slice);

    // 动态字符串
    const hello = try std.fmt.allocPrint(allocator, "Hello, {s}!", .{"Zig"});
    defer allocator.free(hello);

    // 错误处理(可选内存安全)
    const result = allocator.create(i32) catch |err| {
        std.debug.print("内存分配失败: {}\n", .{err});
        return;
    };
}

2.4 错误处理

// 错误类型
const MyError = error{
    InvalidInput,
    OutOfMemory,
    NotFound,
};

// 函数返回错误
fn parseNumber(input: []const u8) !u32 {
    const result = std.fmt.parseInt(u32, input, 10) catch |err| {
        return MyError.InvalidInput;
    };
    return result;
}

// 错误处理
pub fn main() !void {
    // 使用 try
    const num = try parseNumber("42");
    std.debug.print("Number: {}\n", .{num});

    // 捕获错误
    const result = parseNumber("invalid");
    if (result) |value| {
        std.debug.print("Success: {}\n", .{value});
    } else |err| {
        std.debug.print("Error: {}\n", .{err});
    }

    // 错误联合类型
    const value = parseNumber("123") catch |err| {
        std.debug.print("Failed: {}\n", .{err});
        return;
    };
}

2.5 与 C 互操作

// 导入 C 库
const c = @cImport({
    @cInclude("stdio.h");
    @cInclude("stdlib.h");
});

// 使用 C 函数
pub fn main() void {
    c.printf("Hello from C!\n");
    const ptr = c.malloc(100);
    c.free(ptr);
}

// 导出函数给 C 使用
export fn add(a: i32, b: i32) i32 {
    return a + b;
}

// 使用 C 结构体
const c = @cImport({
    @cInclude("time.h");
});

pub fn main() void {
    var tm: c.struct_tm = undefined;
    c.time(&tm);
}

2.6 包管理

// 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,
    });

    // 添加依赖
    exe.addPackagePath("mylib", "libs/mylib.zig");

    b.installArtifact(exe);

    // 运行
    const run_cmd = b.addRunArtifact(exe);
    run_cmd.step.dependOn(b.getInstallStep());

    const run_step = b.step("run", "Run the app");
    run_step.dependOn(&run_cmd.step);
}

⚖️ 第三部分:Zig vs C vs Rust

对比项 Zig C Rust
内存管理手动手动自动(所有权)
编译期计算✅ 强大✅ 有限
✅ 预处理器
跨平台✅ 原生
学习曲线中等陡峭陡峭
适用场景系统编程底层系统安全系统

🧠 第四部分:学习建议

1
前置知识

C 语言基础

2
基础入门

Zig 语法、变量、控制流、函数

3
核心进阶

comptime、内存管理、错误处理、与 C 互操作

4
实战应用

系统工具、嵌入式开发、语言工具链

推荐学习资源


🎯 总结升华

Zig 是系统编程的"新希望"。

它用 编译期计算、无宏、与 C 完美互操作 提供了现代系统编程的新选择。Zig 是 C 语言的有力竞争者。

"Zig 是 C 语言的现代精神继承者。" ⚡

🔖 相关标签
#系统编程 #无宏 #comptime #C 替代 #跨平台 #编译期计算 #嵌入式
📄 本文档为 Zig 完整白皮书 · 最后更新于 2026年06月28日