Zig 是由 Andrew Kelley 于 2016 年创建的系统级编程语言,旨在成为 C 语言的现代替代品。Zig 的设计哲学是 "没有隐藏控制流,没有隐藏内存分配",让程序员完全掌控程序的每个细节。
Zig 的核心定位是 现代系统编程语言。它提供了:
// 注释
// 导入标准库
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});
}
}
// 编译期执行
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)});
}
// 分配器(手动管理)
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;
};
}
// 错误类型
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;
};
}
// 导入 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);
}
// 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 | C | Rust |
|---|---|---|---|
| 内存管理 | 手动 | 手动 | 自动(所有权) |
| 编译期计算 | ✅ 强大 | ❌ | ✅ 有限 |
| 宏 | ❌ | ✅ 预处理器 | ✅ |
| 跨平台 | ✅ 原生 | ✅ | ✅ |
| 学习曲线 | 中等 | 陡峭 | 陡峭 |
| 适用场景 | 系统编程 | 底层系统 | 安全系统 |
C 语言基础
Zig 语法、变量、控制流、函数
comptime、内存管理、错误处理、与 C 互操作
系统工具、嵌入式开发、语言工具链
Zig 是系统编程的"新希望"。
它用 编译期计算、无宏、与 C 完美互操作 提供了现代系统编程的新选择。Zig 是 C 语言的有力竞争者。
"Zig 是 C 语言的现代精神继承者。" ⚡