结构体 (struct)
结构体是 Zig 中最常用的复合数据类型。它们允许你将多个相关的值组合在一起。
定义结构体
const Point = struct {
x: f32,
y: f32,
};
初始化
使用结构体名称和字段初始化列表来创建结构体实例。
const p = Point{
.x = 0.12,
.y = 0.34,
};
默认字段值
字段可以有默认值。
const Vector3 = struct {
x: f32 = 0.0,
y: f32 = 0.0,
z: f32 = 0.0,
};
const v = Vector3{ .z = 1.0 }; // x 和 y 使用默认值
方法
结构体可以包含函数。如果函数的第一个参数是结构体类型本身(或其指针),则可以使用点语法作为方法调用。
const Rectangle = struct {
width: f32,
height: f32,
pub fn area(self: Rectangle) f32 {
return self.width * self.height;
}
};
const rect = Rectangle{ .width = 10.0, .height = 20.0 };
const a = rect.area();
元组 (Tuples)
Zig 中的元组实际上是具有匿名类型和数字字段名的结构体。
const values = .{ 123, "hello", true };
另请参阅:
- Container Level Variables (容器级变量)