struct
// 声明结构体。
// Zig 不保证字段顺序和结构体大小,
// 但保证字段满足 ABI 对齐要求。
const Point = struct {
x: f32,
y: f32,
};
// 声明结构体实例。
const p: Point = .{
.x = 0.12,
.y = 0.34,
};
// 结构体命名空间中的函数可以通过点语法调用。
const Vec3 = struct {
x: f32,
y: f32,
z: f32,
pub fn init(x: f32, y: f32, z: f32) Vec3 {
return Vec3{
.x = x,
.y = y,
.z = z,
};
}
pub fn dot(self: Vec3, other: Vec3) f32 {
return self.x * other.x + self.y * other.y + self.z * other.z;
}
};
test "dot product" {
const v1 = Vec3.init(1.0, 0.0, 0.0);
const v2 = Vec3.init(0.0, 1.0, 0.0);
try expectEqual(0.0, v1.dot(v2));
// 除支持通过点语法调用之外,结构体方法
// 没有特殊之处。可以像结构体内其他声明一样
// 引用它们:
try expectEqual(0.0, Vec3.dot(v1, v2));
}
// 结构体可以包含声明。
// 结构体可以有零个字段。
const Empty = struct {
pub const PI = 3.14;
};
test "struct namespaced variable" {
try expectEqual(3.14, Empty.PI);
try expectEqual(0, @sizeOf(Empty));
// 空结构体也可以按通常方式实例化。
const does_nothing: Empty = .{};
_ = does_nothing;
}
// 字段顺序由编译器决定,但可以从字段指针
// 计算出结构体的基址指针:
fn setYBasedOnX(x: *f32, y: f32) void {
const point: *Point = @fieldParentPtr("x", x);
point.y = y;
}
test "field parent pointer" {
var point = Point{
.x = 0.1234,
.y = 0.5678,
};
setYBasedOnX(&point.x, 0.9);
try expectEqual(0.9, point.y);
}
// 函数可以返回结构体。
fn LinkedList(comptime T: type) type {
return struct {
pub const Node = struct {
prev: ?*Node,
next: ?*Node,
data: T,
};
first: ?*Node,
last: ?*Node,
len: usize,
};
}
test "linked list" {
// 编译时调用的函数会记忆化缓存结果。
try expectEqual(LinkedList(i32), LinkedList(i32));
const list = LinkedList(i32){
.first = null,
.last = null,
.len = 0,
};
try expectEqual(0, list.len);
// 类型是一等值,因此可以将类型赋值给变量,
// 再实例化该类型:
const ListOfInts = LinkedList(i32);
try expectEqual(LinkedList(i32), ListOfInts);
var node = ListOfInts.Node{
.prev = null,
.next = null,
.data = 1234,
};
const list2 = LinkedList(i32){
.first = &node,
.last = &node,
.len = 1,
};
// 使用结构体指针时,可以直接访问字段,
// 无须显式解引用指针。
// 因此可以这样写
try expectEqual(1234, list2.first.?.data);
// 而无须写作 try expectEqual(1234, list2.first.?.*.data);
}
const expectEqual = @import("std").testing.expectEqual;$ zig test test_structs.zig
1/4 test_structs.test.dot product...OK
2/4 test_structs.test.struct namespaced variable...OK
3/4 test_structs.test.field parent pointer...OK
4/4 test_structs.test.linked list...OK
All 4 tests passed.
字段默认值
每个结构体字段都可以带有一个表示默认值的表达式。此类表达式在编译时执行,使得结构体字面量表达式中可以省略该字段:
const Foo = struct {
a: i32 = 1234,
b: i32,
};
test "default struct initialization fields" {
const x: Foo = .{
.b = 5,
};
if (x.a + x.b != 1239) {
comptime unreachable;
}
}$ zig test struct_default_field_values.zig
1/1 struct_default_field_values.test.default struct initialization fields...OK
All 1 tests passed.
错误的字段默认值
仅当初始化时省略某个字段不会破坏结构体的数据不变量时,才适合为该字段提供默认值。
例如,下面是不恰当地使用结构体字段默认初始化的例子:
const Threshold = struct {
minimum: f32 = 0.25,
maximum: f32 = 0.75,
const Category = enum { low, medium, high };
fn categorize(t: Threshold, value: f32) Category {
assert(t.maximum >= t.minimum);
if (value < t.minimum) return .low;
if (value > t.maximum) return .high;
return .medium;
}
};
pub fn main() !void {
var threshold: Threshold = .{
.maximum = 0.20,
};
const category = threshold.categorize(0.90);
std.log.info("category: {t}", .{category});
}
const std = @import("std");
const assert = std.debug.assert;$ zig build-exe bad_default_value.zig
$ ./bad_default_value
thread 509884 panic: reached unreachable code
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/debug.zig:442:14: 0x1029e99 in assert (std.zig)
if (!ok) unreachable; // assertion failure
^
/home/alexrp/Sources/ziglang/zig/doc/langref/bad_default_value.zig:8:15: 0x11e44ba in categorize (bad_default_value.zig)
assert(t.maximum >= t.minimum);
^
/home/alexrp/Sources/ziglang/zig/doc/langref/bad_default_value.zig:19:42: 0x11e2f4e in main (bad_default_value.zig)
const category = threshold.categorize(0.90);
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:788:64: 0x11e3556 in callMain (std.zig)
if (fn_info.param_types.len == 0) return wrapMain(root.main());
^
/home/alexrp/.cache/zig/p/N-V-__8AALBXTRYsilzupvrmv0afm7ohtj5Mj0paqVfKLmfP/lib/std/start.zig:248:5: 0x11e2f01 in _start (std.zig)
asm volatile (switch (native_arch) {
^
(process terminated by signal)
上例展示了忽视该原则的风险:字段默认值破坏了数据不变量,从而导致非法行为。
修复方式是移除所有结构体字段的默认值,并提供一个具名默认值:
const Threshold = struct {
minimum: f32,
maximum: f32,
const default: Threshold = .{
.minimum = 0.25,
.maximum = 0.75,
};
};如果结构体必须使用运行时已知的值才能在不破坏数据不变量的情况下初始化,应提供接收这些运行时值的初始化方法,并由它填充其余字段。
extern struct
extern struct 的内存布局与目标平台的 C ABI 一致。
如果不需要明确定义的内存布局,struct 是更好的选择,因为它对编译器施加的限制更少。
若需要与底层整数具有相同 ABI 的结构体,参见 packed struct;它适合对标志位建模。
另见:
packed struct
packed 结构体与 enum 一样,基于对整数进行不同解释的概念。所有紧凑结构体都有一个底层整数,它可以由字段总位数隐式确定,也可以显式指定。紧凑结构体具有明确定义的内存布局,其 ABI 与底层整数完全相同。
紧凑结构体的每个字段都解释为逻辑位序列,从最低有效位到最高有效位排列。允许的字段类型如下:
- 整数字段使用的位数恰好等于其位宽。例如,
u5会使用底层整数的 5 位。 - bool 字段恰好使用 1 位。
- enum 字段使用的位数恰好等于其整数标记类型的位宽。
- packed union 字段使用的位数恰好等于联合中位宽最大的字段。
packed struct字段使用其底层整数的位。
因此可以对 packed struct 执行 @bitCast 或 @ptrCast 来重新解释内存,甚至可以在编译时这样做:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Full = packed struct {
number: u16,
};
const Divided = packed struct {
half1: u8,
quarter3: u4,
quarter4: u4,
};
test "@bitCast between packed structs" {
try doTheTest();
try comptime doTheTest();
}
fn doTheTest() !void {
try expectEqual(2, @sizeOf(Full));
try expectEqual(2, @sizeOf(Divided));
const full = Full{ .number = 0x1234 };
const divided: Divided = @bitCast(full);
try expectEqual(0x34, divided.half1);
try expectEqual(0x2, divided.quarter3);
try expectEqual(0x1, divided.quarter4);
const ordered: [2]u8 = @bitCast(full);
try expectEqual(0x34, ordered[0]);
try expectEqual(0x12, ordered[1]);
}$ zig test test_packed_structs.zig
1/1 test_packed_structs.test.@bitCast between packed structs...OK
All 1 tests passed.
底层整数可以推导,也可以显式提供。推导时使用无符号整数;显式提供时,会在编译时强制检查其位宽恰好等于全部字段的总位宽:
test "missized packed struct" {
const S = packed struct(u32) { a: u16, b: u8 };
_ = S{ .a = 4, .b = 2 };
}$ zig test test_missized_packed_struct.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_missized_packed_struct.zig:2:22: error: backing integer bit width does not match total bit width of fields
const S = packed struct(u32) { a: u16, b: u8 };
~~~~~~~^~~~~~~~~~~~~~~~~~~~~~~~~~~~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_missized_packed_struct.zig:2:29: note: backing integer 'u32' has bit width '32'
const S = packed struct(u32) { a: u16, b: u8 };
^~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_missized_packed_struct.zig:2:22: note: struct fields have total bit width '24'
referenced by:
test.missized packed struct: /home/alexrp/Sources/ziglang/zig/doc/langref/test_missized_packed_struct.zig:3:17
可以使用 @backingInt 和 @fromBackingInt 在 packed struct 与其底层整数之间相互转换:
const std = @import("std");
const assert = std.debug.assert;
const expectEqual = std.testing.expectEqual;
const PackedStruct = packed struct(u8) {
lo: u4,
hi: u4,
};
test "convert to and from backing integer" {
const original: PackedStruct = .{ .lo = 0b1100, .hi = 0b0101 };
const backing_int = @backingInt(original);
comptime assert(@TypeOf(backing_int) == u8);
try expectEqual(0b0101_1100, backing_int);
const reconstructed: PackedStruct = @fromBackingInt(backing_int);
try expectEqual(original, reconstructed);
}$ zig test test_packed_struct_backing_int.zig
1/1 test_packed_struct_backing_int.test.convert to and from backing integer...OK
All 1 tests passed.
Zig 允许获取未按字节对齐的字段的地址:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var foo = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-byte-aligned field" {
const ptr = &foo.b;
try expectEqual(2, ptr.*);
}$ zig test test_pointer_to_non-byte_aligned_field.zig
1/1 test_pointer_to_non-byte_aligned_field.test.pointer to non-byte-aligned field...OK
All 1 tests passed.
但指向未按字节对齐字段的指针具有特殊属性,不能传入需要普通指针的位置:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointer to non-byte-aligned field" {
try expectEqual(2, bar(&bit_field.b));
}
fn bar(x: *const u3) u3 {
return x.*;
}$ zig test test_misaligned_pointer.zig
/home/alexrp/Sources/ziglang/zig/doc/langref/test_misaligned_pointer.zig:17:28: error: expected type '*const u3', found '*align(1:3:1) u3'
try expectEqual(2, bar(&bit_field.b));
^~~~~~~~~~~~
/home/alexrp/Sources/ziglang/zig/doc/langref/test_misaligned_pointer.zig:17:28: note: pointer host size '1' cannot cast into pointer host size '0'
/home/alexrp/Sources/ziglang/zig/doc/langref/test_misaligned_pointer.zig:17:28: note: pointer bit offset '3' cannot cast into pointer bit offset '0'
/home/alexrp/Sources/ziglang/zig/doc/langref/test_misaligned_pointer.zig:20:11: note: parameter type declared here
fn bar(x: *const u3) u3 {
^~~~~~~~~
此处无法调用函数 bar,因为指向未满足 ABI 对齐要求的字段的指针包含位偏移信息,而函数要求满足 ABI 对齐要求的指针。
指向未满足 ABI 对齐要求的字段的指针,与同一承载整数中的其他字段共享地址:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
var bit_field = BitField{
.a = 1,
.b = 2,
.c = 3,
};
test "pointers of sub-byte-aligned fields share addresses" {
try expectEqual(@intFromPtr(&bit_field.a), @intFromPtr(&bit_field.b));
try expectEqual(@intFromPtr(&bit_field.a), @intFromPtr(&bit_field.c));
}$ zig test test_packed_struct_field_address.zig
1/1 test_packed_struct_field_address.test.pointers of sub-byte-aligned fields share addresses...OK
All 1 tests passed.
可以通过 @bitOffsetOf 和 offsetOf 观察这一点:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const BitField = packed struct {
a: u3,
b: u3,
c: u2,
};
test "offsets of non-byte-aligned fields" {
comptime {
try expectEqual(0, @bitOffsetOf(BitField, "a"));
try expectEqual(3, @bitOffsetOf(BitField, "b"));
try expectEqual(6, @bitOffsetOf(BitField, "c"));
try expectEqual(0, @offsetOf(BitField, "a"));
try expectEqual(0, @offsetOf(BitField, "b"));
try expectEqual(0, @offsetOf(BitField, "c"));
}
}$ zig test test_bitOffsetOf_offsetOf.zig
1/1 test_bitOffsetOf_offsetOf.test.offsets of non-byte-aligned fields...OK
All 1 tests passed.
紧凑结构体的对齐要求与其底层整数相同,不过,指向紧凑结构体且具有更大对齐值的指针可以覆盖此要求:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const S = packed struct {
a: u32,
b: u32,
};
test "overaligned pointer to packed struct" {
var foo: S align(4) = .{ .a = 1, .b = 2 };
const ptr: *align(4) S = &foo;
const ptr_to_b = &ptr.b;
try expectEqual(2, ptr_to_b.*);
}$ zig test test_overaligned_packed_struct.zig
1/1 test_overaligned_packed_struct.test.overaligned pointer to packed struct...OK
All 1 tests passed.
也可以设置结构体字段的对齐要求:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "aligned struct fields" {
const S = struct {
a: u32 align(2),
b: u32 align(64),
};
var foo = S{ .a = 1, .b = 2 };
try expectEqual(64, @alignOf(S));
try expectEqual(*align(2) u32, @TypeOf(&foo.a));
try expectEqual(*align(64) u32, @TypeOf(&foo.b));
}$ zig test test_aligned_struct_fields.zig
1/1 test_aligned_struct_fields.test.aligned struct fields...OK
All 1 tests passed.
紧凑结构体的相等性比较会比较底层整数,并且只支持 == 和 != 这两个运算符。
const std = @import("std");
const expectEqual = std.testing.expectEqual;
test "packed struct equality" {
const S = packed struct {
a: u4,
b: u4,
};
const x: S = .{ .a = 1, .b = 2 };
const y: S = .{ .b = 2, .a = 1 };
try expectEqual(x, y);
}$ zig test test_packed_struct_equality.zig
1/1 test_packed_struct_equality.test.packed struct equality...OK
All 1 tests passed.
字段访问与赋值可以理解为底层整数位移操作的简写。这些操作不是原子操作,因此与内存映射输入输出(MMIO)结合时应谨慎使用字段访问语法。对于 volatile 指针,应先构造完整的新值,再将它写入易失指针,而不是直接访问字段。
pub const GpioRegister = packed struct(u8) {
GPIO0: bool,
GPIO1: bool,
GPIO2: bool,
GPIO3: bool,
reserved: u4 = 0,
};
const gpio: *volatile GpioRegister = @ptrFromInt(0x0123);
pub fn writeToGpio(new_states: GpioRegister) void {
// 不应采用的写法示例:
// 错误!gpio.GPIO0 = true; 错误!
// 应改为这样:
gpio.* = new_states;
}结构体命名
所有结构体都是匿名的,因此 Zig 根据若干规则推导类型名称。
- 如果结构体出现在变量的初始化表达式中,就以该变量命名。
- 如果结构体出现在
return表达式中,就以返回它的函数命名,并将参数值序列化后包含在名称中。 - 其他情况下,结构体会获得类似
(filename.funcname__struct_ID)的名称。 - 结构体声明于另一个结构体内部时,其名称由父结构体名称与上述规则推导的名称组成,中间以点分隔。
const std = @import("std");
pub fn main() void {
const Foo = struct {};
std.debug.print("variable: {s}\n", .{@typeName(Foo)});
std.debug.print("anonymous: {s}\n", .{@typeName(struct {})});
std.debug.print("function: {s}\n", .{@typeName(List(i32))});
}
fn List(comptime T: type) type {
return struct {
x: T,
};
}$ zig build-exe struct_name.zig
$ ./struct_name
variable: struct_name.main.Foo
anonymous: struct_name.main__struct_786
function: struct_name.List(i32)
匿名结构体字面量
Zig 允许省略字面量中的结构体类型。对结果执行类型强制转换时,结构体字面量会直接初始化结果位置,不发生复制:
const std = @import("std");
const expectEqual = std.testing.expectEqual;
const Point = struct { x: i32, y: i32 };
test "anonymous struct literal" {
const pt: Point = .{
.x = 13,
.y = 67,
};
try expectEqual(13, pt.x);
try expectEqual(67, pt.y);
}$ zig test test_struct_result.zig
1/1 test_struct_result.test.anonymous struct literal...OK
All 1 tests passed.
结构体类型可以推导。此处结果位置没有提供类型,因此 Zig 推导类型:
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "fully anonymous struct" {
try check(.{
.int = @as(u32, 1234),
.float = @as(f64, 12.34),
.b = true,
.s = "hi",
});
}
fn check(args: anytype) !void {
try expectEqual(1234, args.int);
try expectEqual(12.34, args.float);
try expect(args.b);
try expectEqual('h', args.s[0]);
try expectEqual('i', args.s[1]);
}$ zig test test_anonymous_struct.zig
1/1 test_anonymous_struct.test.fully anonymous struct...OK
All 1 tests passed.
元组
创建匿名结构体时可以不指定字段名称,这种结构体称为“元组”。空元组写作 .{},可见于“你好,世界”示例。
字段隐式使用从 0 开始的数字命名。由于名称是整数,使用 . 语法访问时必须将名称包在 @"" 中。@"" 中的名称始终识别为标识符。
与数组类似,元组具有 .len 字段,可以索引(前提是索引在编译时已知),也支持 ++ 运算符。还可以使用 inline for 迭代。
const std = @import("std");
const expect = std.testing.expect;
const expectEqual = std.testing.expectEqual;
test "tuple" {
const values = .{
@as(u32, 1234),
@as(f64, 12.34),
true,
"hi",
} ++ .{ false, false };
try expectEqual(1234, values[0]);
try expectEqual(false, values[4]);
inline for (values, 0..) |v, i| {
if (i != 2) continue;
try expect(v);
}
try expectEqual(6, values.len);
try expectEqual('h', values.@"3"[0]);
}$ zig test test_tuples.zig
1/1 test_tuples.test.tuple...OK
All 1 tests passed.
元组解构
元组可以解构。
需要从块中返回多个值时,元组解构很有用:
const print = @import("std").debug.print;
pub fn main() void {
const digits = [_]i8 { 3, 8, 9, 0, 7, 4, 1 };
const min, const max = blk: {
var min: i8 = 127;
var max: i8 = -128;
for (digits) |digit| {
if (digit < min) min = digit;
if (digit > max) max = digit;
}
break :blk .{ min, max };
};
print("min = {}\n", .{ min });
print("max = {}\n", .{ max });
}$ zig build-exe destructuring_block.zig
$ ./destructuring_block
min = 0
max = 9
处理以元组返回多个值的函数和内置函数时,元组解构很有用:
const print = @import("std").debug.print;
fn divmod(numerator: u32, denominator: u32) struct { u32, u32 } {
return .{ numerator / denominator, numerator % denominator };
}
pub fn main() void {
const div, const mod = divmod(10, 3);
print("10 / 3 = {}\n", .{div});
print("10 % 3 = {}\n", .{mod});
}$ zig build-exe destructuring_return_value.zig
$ ./destructuring_return_value
10 / 3 = 3
10 % 3 = 1
另见:
另见: