块
块用于限制变量声明的作用域:
test "access variable after block scope" {
{
var x: i32 = 1;
_ = &x;
}
x += 1;
}$ zig test test_blocks.zig
/home/andy/src/zig/doc/langref/test_blocks.zig:6:5: error: use of undeclared identifier 'x'
x += 1;
^
块是表达式。为块添加标签后,可以使用 break 从块返回值:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "labeled break from labeled block expression" {
var y: i32 = 123;
const x = blk: {
y += 1;
break :blk y;
};
try expectEqual(124, x);
try expectEqual(124, y);
}$ zig test test_labeled_break.zig
1/1 test_labeled_break.test.labeled break from labeled block expression...OK
All 1 tests passed.
此处 blk 可以是任意名称。
另见:
名称遮蔽
标识符绝不允许通过使用相同名称来“隐藏”其他标识符:
const pi = 3.14;
test "inside test block" {
// 甚至再进入另一个块
{
var pi: i32 = 1234;
}
}$ zig test test_shadowing.zig
/home/andy/src/zig/doc/langref/test_shadowing.zig:6:13: error: local variable shadows declaration of 'pi'
var pi: i32 = 1234;
^~
/home/andy/src/zig/doc/langref/test_shadowing.zig:1:1: note: declared here
const pi = 3.14;
^~~~~~~~~~~~~~~
因此,阅读 Zig 代码时,可以确信标识符在其定义的作用域内始终具有相同含义。不过,在彼此独立的作用域中可以使用相同名称:
test "separate scopes" {
{
const pi = 3.14;
_ = pi;
}
{
var pi: bool = true;
_ = π
}
}$ zig test test_scopes.zig
1/1 test_scopes.test.separate scopes...OK
All 1 tests passed.
空块
空块返回 void 类型唯一的值:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test {
const a = {};
try expectEqual(void, @TypeOf(a));
}$ zig test test_empty_block.zig
1/1 test_empty_block.test_0...OK
All 1 tests passed.