Zig 简介

写代码的西瓜

github.com/jiacai2050

2024-01-20

1. Zig 特点

Zig 是一种通用编程语言和工具链,用于维护稳健、优化和可重复使用的软件

Better C

1.1. 简洁

  • 没有隐藏的控制流

    var a = b + c.d;
    foo();
    bar();
    
  • 没有隐藏内存分配
  • 没有预处理器,没有宏
    • comptime 编译期执行

1.2. comptime

基于编译时代码执行和懒惰评估的元编程新方法

  • 在编译时调用任何函数
  • 将类型作为值进行操作,无需运行时开销

1.3. 与 C/C++ 结合紧密的工具链

  • Zig 用作零依赖、即插即用的 C/C++ 编译器,支持开箱即用的交叉编译
  • 在 C/C++ 项目中添加 Zig 编译单元;默认情况下启用跨语言 LTO
  • 利用 zig build 在所有平台上创建一致的开发环境

2. 示例代码

2.1. Hello World

const std = @import("std");
pub fn main() void {
    std.debug.print("Hello World", .{});
}

2.2. 逐行读取文件

const file = try fs.cwd().openFile("test.txt", .{});
defer file.close();
const reader = file.reader();

var line = std.ArrayList(u8).init(allocator);
defer line.deinit();
const writer = line.writer();
var line_no: usize = 1;
while (reader.streamUntilDelimiter(writer, '\n', null)) : (line_no += 1) {
    defer line.clearRetainingCapacity();
    print("{d}--{s}\n", .{ line_no, line.items });
} else |err| switch (err) {
    error.EndOfStream => {}, // Continue on
    else => |e| return e, // Propagate error
}

来源:Zig cookbook

2.3. 基于 Comptime 的 List

fn LinkedList(comptime T: type) type {
    return struct {
        pub const Node = struct {
            prev: ?*Node,
            next: ?*Node,
            data: T,
        };

        first: ?*Node,
        last:  ?*Node,
        len:   usize,
    };
}
const ListOfInts = LinkedList(i32);
try expect(ListOfInts == LinkedList(i32));

var node = ListOfInts.Node {
    .prev = null,
    .next = null,
    .data = 1234,
};
var list2 = LinkedList(i32) {
    .first = &node,
    .last = &node,
    .len = 1,
};

2.4. 与 C 交互

const ray = @cImport({
    @cInclude("raylib.h");
});
pub fn main() void {
    const screenWidth = 800;
    const screenHeight = 450;
    ray.InitWindow(screenWidth, screenHeight, "raylib [core] example - basic window");
    defer ray.CloseWindow();
    ray.SetTargetFPS(60);
    while (!ray.WindowShouldClose()) {
        ray.BeginDrawing();
        defer ray.EndDrawing();

        ray.ClearBackground(ray.RAYWHITE);
        ray.DrawText("Hello, World!", 190, 200, 20, ray.LIGHTGRAY);
    }
}
$ zig build-exe main.zig -lc $(pkg-config --cflags --libs raylib)
$ ./main
raylib-demo.webp

3. Zig in production

Uber
Bootstrapping Uber’s Infrastructure on arm64 with Zig
Bun
另一个 JavaScript 运行时
Mach
游戏引擎
Tigerbeetle
分布式帐务数据库
The Roc Programming Language

4. 学习资料

学习 Zig
一个体系完整的 Zig 的入门教程
Zig 语言圣经
全面、深入、实用的 Zig 学习指南
ziglings/exercises
通过修复损坏的小程序来学习 Zig 编程语言
Zig Cookbook
如何用 Zig 来完成常见的编程任务
zigcc/awesome-zig
流行的 Zig 项目

ZigCC

zigcc-mp.webp