跳转到内容
语言参考Zig 0.17.0官方原文

裸 union 以字段列表定义一个值可能具有的类型集合。同一时刻只有一个字段可以处于活动状态。裸联合的内存表示没有保证,因此不能用它重新解释内存。如需这样做,应使用 @ptrCast,或者具有明确内存布局保证的 extern union 或 packed union。访问非活动字段属于带安全检查的非法行为:

test_wrong_union_access.zig
const Payload = union {
int: i64,
float: f64,
boolean: bool,
};
test "simple union" {
var payload = Payload{ .int = 1234 };
payload.float = 12.34;
}
命令行
$ zig test test_wrong_union_access.zig
1/1 test_wrong_union_access.test.simple union...thread 702527 panic: access of union field 'float' while field 'int' is active
/home/andy/src/zig/doc/langref/test_wrong_union_access.zig:8:12: 0x124c5b2 in test.simple union (test_wrong_union_access.zig)
payload.float = 12.34;
^
/home/andy/src/zig/lib/compiler/test_runner.zig:295:25: 0x1200951 in mainTerminal (test_runner.zig)
if (test_fn.func()) |_| {
^
/home/andy/src/zig/lib/compiler/test_runner.zig:74:28: 0x1200132 in main (test_runner.zig)
return mainTerminal(init);
^
/home/andy/src/zig/lib/std/start.zig:789:88: 0x11fc8cf in callMain (std.zig)
if (fn_info.param_types[0].? == std.process.Init.Minimal) return wrapMain(root.main(.{
^
/home/andy/src/zig/lib/std/start.zig:248:5: 0x11fc2b1 in _start (std.zig)
asm volatile (switch (native_arch) {
^
error: the following test command terminated with signal ABRT:
/home/andy/src/zig/.zig-cache/o/3cd42cabbbbd074f62109e69e5f19f42/test --seed=0x62c14365

对整个联合赋值可以激活另一个字段:

test_simple_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Payload = union {
int: i64,
float: f64,
boolean: bool,
};
test "simple union" {
var payload = Payload{ .int = 1234 };
try expectEqual(1234, payload.int);
payload = Payload{ .float = 12.34 };
try expectEqual(12.34, payload.float);
}
命令行
$ zig test test_simple_union.zig
1/1 test_simple_union.test.simple union...OK
All 1 tests passed.

要对联合使用 switch,它必须是标记联合或 packed union。

当标记名称在编译时已知时,初始化联合的方法参见 @unionInit。

标记联合

联合可以声明枚举标记类型,使其成为标记联合,从而能够用于 switch 表达式。匹配标记联合时,可通过额外捕获取得标记值。标记联合可以强制转换为其标记类型,参见类型强制转换:联合与枚举。

test_tagged_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "switch on tagged union" {
const c = ComplexType{ .ok = 42 };
try expectEqual(ComplexTypeTag.ok, @as(ComplexTypeTag, c));
switch (c) {
.ok => |value| try expectEqual(42, value),
.not_ok => unreachable,
}
switch (c) {
.ok => |_, tag| {
// 由于位于 '.ok' 分支,编译时已知 'tag' 为 '.ok':
comptime std.debug.assert(tag == .ok);
},
.not_ok => unreachable,
}
}
test "get tag type" {
try expectEqual(ComplexTypeTag, std.meta.Tag(ComplexType));
}
命令行
$ zig test test_tagged_union.zig
1/2 test_tagged_union.test.switch on tagged union...OK
2/2 test_tagged_union.test.get tag type...OK
All 2 tests passed.

如果要在 switch 表达式中修改标记联合的载荷,在变量名前添加 *,使其成为指针:

test_switch_modify_tagged_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const ComplexTypeTag = enum {
ok,
not_ok,
};
const ComplexType = union(ComplexTypeTag) {
ok: u8,
not_ok: void,
};
test "modify tagged union in switch" {
var c = ComplexType{ .ok = 42 };
switch (c) {
ComplexTypeTag.ok => |*value| value.* += 1,
ComplexTypeTag.not_ok => unreachable,
}
try expectEqual(43, c.ok);
}
命令行
$ zig test test_switch_modify_tagged_union.zig
1/1 test_switch_modify_tagged_union.test.modify tagged union in switch...OK
All 1 tests passed.

可以让联合推导枚举标记类型。此外,联合与结构体、枚举一样,也可以包含方法。

test_union_method.zig
const std = @import("std");
const expect = std.testing.expect;
const Variant = union(enum) {
int: i32,
boolean: bool,
// 推导枚举标记类型时可以省略 void。
none,
fn truthy(self: Variant) bool {
return switch (self) {
Variant.int => |x_int| x_int != 0,
Variant.boolean => |x_bool| x_bool,
Variant.none => false,
};
}
};
test "union method" {
var v1: Variant = .{ .int = 1 };
var v2: Variant = .{ .boolean = false };
var v3: Variant = .none;
try expect(v1.truthy());
try expect(!v2.truthy());
try expect(!v3.truthy());
}
命令行
$ zig test test_union_method.zig
1/1 test_union_method.test.union method...OK
All 1 tests passed.

使用推导枚举标记类型的联合,也可以为推导出的标记指定序数值。这要求为标记显式指定整数类型。可使用 @backingInt 访问活动字段对应的序数值。

test_tagged_union_with_tag_values.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Tagged = union(enum(u32)) {
int: i64 = 123,
boolean: bool = 67,
};
test "tag values" {
const int: Tagged = .{ .int = -40 };
try expectEqual(123, @backingInt(int));
const boolean: Tagged = .{ .boolean = false };
try expectEqual(67, @backingInt(boolean));
}
命令行
$ zig test test_tagged_union_with_tag_values.zig
1/1 test_tagged_union_with_tag_values.test.tag values...OK
All 1 tests passed.

@tagName 可以返回在编译时表示字段名称的 [:0]const u8 值:

test_tagName.zig
const std = @import("std");
const expectEqualSlices = std.testing.expectEqualSlices;
const Small2 = union(enum) {
a: i32,
b: bool,
c: u8,
};
test "@tagName" {
try expectEqualSlices(u8, "a", @tagName(Small2.a));
}
命令行
$ zig test test_tagName.zig
1/1 test_tagName.test.@tagName...OK
All 1 tests passed.

extern union

extern union 的内存布局保证与目标 C ABI 兼容。

另见:

packed union

packed union 具有明确定义的内存布局,可以包含在 packed struct 中。

紧凑联合的全部字段必须具有相同的 @bitSizeOf。

紧凑联合的相等性比较会比较底层整数,并且只支持 == 和 != 这两个运算符。

test_packed_union_equality.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "packed union equality" {
const U = packed union {
a: u4,
b: i4,
};
const x: U = .{ .a = 3 };
const y: U = .{ .b = 3 };
try expectEqual(x, y);
}
命令行
$ zig test test_packed_union_equality.zig
1/1 test_packed_union_equality.test.packed union equality...OK
All 1 tests passed.

另见:

匿名联合字面量

使用匿名结构体字面量语法,可以在不指定类型的情况下初始化联合:

test_anonymous_union.zig
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Number = union {
int: i32,
float: f64,
};
test "anonymous union literal syntax" {
const i: Number = .{ .int = 42 };
const f = makeNumber();
try expectEqual(42, i.int);
try expectEqual(12.34, f.float);
}
fn makeNumber() Number {
return .{ .float = 12.34 };
}
命令行
$ zig test test_anonymous_union.zig
1/1 test_anonymous_union.test.anonymous union literal syntax...OK
All 1 tests passed.