云计算百科
云计算领域专业知识百科平台

Zig 系统编程也能如此简单四:控制流:一切都是表达式

第 4 章 控制流:一切都是表达式

本章目标:掌握 Zig 的控制流。核心心智模型只有一句话——if、switch、块 {}、甚至 while 都能当表达式用,会\”求出一个值\”。理解这一点,你的 Zig 代码会立刻变得紧凑。


4.1 if:三分身

Zig 的 if 有三种完全不同的用法,新手最容易混淆:

① 普通布尔判断

const std = @import(\”std\”);

pub fn main() !void {
// 注意:这里如果写 main(init: std.process.Init) 却不用 init,
// 会得到 \”unused function parameter\” 编译错误 —— main 也不例外!
const n = try std.fmt.parseInt(i32, \”42\”, 10);

// 作为语句
if (n > 0) {
std.debug.print(\”正数\\n\”, .{});
} else if (n < 0) {
std.debug.print(\”负数\\n\”, .{});
} else {
std.debug.print(\”零\\n\”, .{});
}

// 作为表达式(两个分支类型必须兼容)
const sign: i32 = if (n > 0) 1 else if (n < 0) -1 else 0;
std.debug.print(\”sign = {d}\\n\”, .{sign});
}

[stderr]
正数
sign = 1

⚠️ 条件必须是 bool,不能是\”真值\”。if (some_pointer)、if (some_int) 都是编译错误。这是 Zig 拒绝隐式转换的一部分。

💡 顺带一个新手必踩的坑:main 的参数也不例外。如果你写了 pub fn main(init: std.process.Init) !void 却没用到 init,编译器会报 unused function parameter。要么改回无参 main(),要么在函数体开头写 _ = init;。本书的示例会在不需要 I/O 时用无参 main(),需要时用 init.io / init.gpa。

② 可选值解包(if (x) |v|)

const std = @import(\”std\”);

fn parseAge(s: []const u8) ?u8 {
return std.fmt.parseInt(u8, s, 10) catch null;
}

pub fn main() !void {
// 有值时捕获,null 时走 else
if (parseAge(\”25\”)) |age| {
std.debug.print(\”年龄 = {d}\\n\”, .{age});
} else {
std.debug.print(\”解析失败\\n\”, .{});
}

if (parseAge(\”abc\”)) |age| {
std.debug.print(\”年龄 = {d}\\n\”, .{age});
} else {
std.debug.print(\”解析失败(走这里)\\n\”, .{});
}

// 表达式形式:注意捕获到的是值,不是指针
const a = if (parseAge(\”30\”)) |v| v else 0;
std.debug.print(\”a = {d}\\n\”, .{a});

// 想要指针?用 `|*v|`
var maybe: ?u8 = 7;
if (maybe) |*v| {
v.* = 9; // 直接修改原变量
}
std.debug.print(\”修改后 maybe = {?d}\\n\”, .{maybe});
}

[stderr]
年龄 = 25
解析失败(走这里)
a = 30
修改后 maybe = 9

③ 错误联合解包(if (x) |v| else |e|)

const std = @import(\”std\”);

const ParseError = error{ InvalidDigit, Empty };

fn strictParse(s: []const u8) ParseError!u32 {
if (s.len == 0) return error.Empty;
var result: u32 = 0;
for (s) |c| {
if (c < \’0\’ or c > \’9\’) return error.InvalidDigit;
result = result * 10 + (c – \’0\’);
}
return result;
}

pub fn main() !void {
// 成功捕获值,失败捕获错误
if (strictParse(\”123\”)) |v| {
std.debug.print(\”① 成功 = {d}\\n\”, .{v});
} else |e| {
std.debug.print(\”① 失败 = {s}\\n\”, .{@errorName(e)});
}

if (strictParse(\”12x\”)) |v| {
std.debug.print(\”② 成功 = {d}\\n\”, .{v});
} else |e| {
std.debug.print(\”② 失败 = {s}\\n\”, .{@errorName(e)});
}

// 表达式形式
const value = strictParse(\”456\”) catch |e| blk: {
std.debug.print(\”(出错 {s},用默认值)\\n\”, .{@errorName(e)});
break :blk 0;
};
std.debug.print(\”value = {d}\\n\”, .{value});
}

[stderr]
① 成功 = 123
② 失败 = InvalidDigit
value = 456


4.2 switch:必须穷尽,且是表达式

Zig 的 switch 和 C 的完全不同:没有 fallthrough、必须穷尽所有情况、每个分支是一个表达式、整个 switch 也是一个表达式。

const std = @import(\”std\”);

const Color = enum { red, green, blue, alpha };
const Value = union(enum) { int: i64, text: []const u8, none };

fn describe(c: Color) []const u8 {
return switch (c) {
.red => \”红色\”,
.green => \”绿色\”,
.blue => \”蓝色\”,
.alpha => \”透明\”,
// 枚举必须全部列出,否则编译错误(除非用 else)
};
}

fn show(v: Value, arena: std.mem.Allocator) ![]const u8 {
return switch (v) {
.int => |n| try arena.print(\”{d}\”, .{n}), // 需要分配 -> 传分配器
.text => |t| t,
.none => \”(无)\”,
};
}

pub fn main(init: std.process.Init) !void {
const arena = init.arena.allocator();

inline for (.{ Color.red, Color.green, Color.blue, Color.alpha }) |c| {
std.debug.print(\”{s} -> {s}\\n\”, .{ @tagName(c), describe(c) });
}

// 多值匹配、范围匹配
const n: i32 = 42;
const bucket = switch (n) {
0 => \”零\”,
1, 2, 3 => \”小\”,
4…10 => \”中\”, // 闭区间范围
11…std.math.maxInt(i32) => \”大\”,
else => \”负数\”,
};
std.debug.print(\”42 -> {s}\\n\”, .{bucket});

// 捕获载荷(配合 tagged union,见第 6 章)
const value: Value = .{ .int = 7 };
std.debug.print(\”payload -> {s}\\n\”, .{try show(value, arena)});
}

const std = @import(\”std\”);

const Op = enum { add, sub, mul, div };

fn apply(comptime op: Op, a: f64, b: f64) f64 {
return switch (op) {
.add => a + b,
.sub => a – b,
.mul => a * b,
.div => a / b,
};
}

pub fn main() !void {
// inline switch:每个分支生成一份特化代码,op 是编译期常量
inline for (.{ Op.add, Op.sub, Op.mul, Op.div }) |op| {
const r = apply(op, 10, 4);
std.debug.print(\”{s:>3}(10, 4) = {d}\\n\”, .{ @tagName(op), r });
}
}

[stderr]
add(10, 4) = 14
sub(10, 4) = 6
mul(10, 4) = 40
div(10, 4) = 2.5

⚠️ @tagName 返回的是 [:0]const u8,可以直接用 {s} 打印。这是调试枚举/tagged union 最好用的函数。


4.3 while:条件、继续表达式、else

Zig 的 while 有一个别的语言没有的东

赞(0)
未经允许不得转载:网硕互联帮助中心 » Zig 系统编程也能如此简单四:控制流:一切都是表达式
分享到: 更多 (0)

评论 抢沙发

评论前必须登录!