01
快速上手
Hello World
Zig 用 @import 引入标准库;print 使用 comptime 格式字符串。
zig
const std = @import("std");
pub fn main() void {
std.debug.print("Hello, {s}\n", .{"World"}});
}变量
const 不可变,var 可变。类型可显式声明或自动推断。
zig
const x: i32 = 10;
var y: i32 = 20;
y += 5;函数
函数用 fn 关键字;pub 使其公开。
zig
fn add(a: i32, b: i32) i32 {
return a + b;
}
pub fn main() void {
const std = @import("std");
std.debug.print("{d}\n", .{add(3, 4)});
}构建
Zig 内置构建系统并支持交叉编译。
zig
# zig build-exe main.zig
# zig run main.zig02
类型
整数
Zig 支持任意位宽的整数:i8、u8、i16、u16、i32、u32 等。
zig
const a: u8 = 255;
const b: i32 = -100;
const c: usize = 0;数组
[_] 自动推断数组长度。
zig
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const first = arr[0];
const len = arr.len;切片
切片是数组的视图;.. 表示不含端点。
zig
const arr = [_]i32{ 1, 2, 3, 4, 5 };
const slice = arr[1..4]; // [2, 3, 4]可选类型
?T 是可选类型;用 .? 或 if-let 解包。
zig
var maybe: ?i32 = null;
maybe = 42;
if (maybe) |val| {
// val is i32 here
}03
控制流
If-Else
在 Zig 中 if-else 是表达式。
zig
const x: i32 = 5;
if (x > 3) {
// big
} else {
// small
}Switch
switch 必须穷尽所有情况。
zig
const x: u8 = 2;
switch (x) {
1 => {},
2 => {},
else => {},
}While
: (i += 1) 是 continue 表达式。
zig
var i: u32 = 0;
while (i < 5) : (i += 1) {
// loop body
}For
for 遍历切片/数组。
zig
const arr = [_]i32{ 1, 2, 3 };
for (arr) |val| {
// use val
}04
内存
分配器
Zig 没有隐藏的内存分配;分配器是显式传入的。
zig
const std = @import("std");
pub fn main() !void {
var gpa = std.heap.GeneralPurposeAllocator(.{}){};
const allocator = gpa.allocator();
const slice = try allocator.alloc(u8, 100);
defer allocator.free(slice);
}Defer
defer 在作用域结束时执行——类 RAII 的资源清理。
zig
const std = @import("std");
pub fn main() void {
const file = std.fs.cwd().createFile("test.txt", .{}) catch unreachable;
defer file.close();
}这篇内容对您有帮助吗?