Zig 语言中的类型化索引模式
来源标题:Typed Indices in Zig
Zig 社区讨论的 named integer 或 Newtype Index 模式可防止在不同数组之间混用索引。作者认为现有示例未能充分展示调用点的安全性,因为调用者仍可用 backingInt 取出数值索引并传给错误数组。实际使用该模式需要配合 getter 辅助方法,把索引类型绑定到数组类型上,从而在编译期拒绝错误类型。
以下正文由 AI 翻译自 Hacker News 最新(原文版权归原站所有),可能存在偏差,重要内容请以原文为准。
命名整数或 Newtype Index 模式可以防止在不同数组之间混用索引。
上面的例子对我来说并没有特别大的启发。Andrew 的例子没有展示太多如何在调用点强制实施安全性:任何调用者都可以调用 backingInt(以前是 @intFromEnum)来恢复出一个数值索引,然后把它传给错误的数组,或者直接用普通整数访问数组元素。而 matklad 的例子侧重于以一种优雅的方式构建树形数据结构,但那和混用数组索引这个入门问题完全是两码事,所以对我来说并不是一个特别有说服力的例证。
在实践中,要好好利用这个模式,需要一个 getter 辅助函数作为访问数组元素的常规方式。它可以是数组类型上的方法——也可以是索引类型上的方法。
// Declaration
const Elem = struct {...};
const Array = struct {
items: []Elem,
const Index = enum(u32) { _ };
fn get(a: *Array, i: Index) *Elem {
return &a.items[@backingInt(i)];
}
};
// Usage
const a = Array{ .items = &.{...} };
var i: Index = @fromBackingInt(57);
_ = a.get(i);
_ = a.get(57); // Does not compile: wrong type.
_ = a[57]; // Possible, but discouraged by the existence of `Array.get`.
数组结构体(struct of array)示例
在数组结构体这种数据结构中,为每个切片配备一个类型化索引(而不是依赖小心翼翼的命名)尤其有价值。
考虑这个电子表格的例子,其中很容易混用索引:
pub const Sheet = struct {
row_height: []f32,
col_width: []f32,
};
var s: Sheet = .{...};
var r: usize = 0; // Row index.
var c: usize = 0; // Column index.
// User changes the column width.
s.col_width[r].* = new_col_width; // bug: access row data with a column indice!
我们可以通过强制在编译时用类型化索引检查字段访问来防止这类 bug。
pub const Sheet = struct {
row_height: []f32,
col_width: []f32,
pub const Row = enum(u32) { _ };
pub const Column = enum(u32) { _ };
pub fn getRowHeight(s: *Sheet, r: Row) *f32 {
return &s[@backingInt(r)];
}
pub fn getColWidth(s: *Sheet, c: Column) *f32 {
return &s[@backingInt(c)];
}
};
var s: Sheet = .{ ... };
var r: Sheet.Row = @fromBackingInt(0); // Typed row index.
var c: Sheet.Column = @fromBackingInt(0); // Typed column index.
// User changes the column width.
const new_col_width: f32 = undefined;
s.getColWidth(r).* = new_col_width; // Comptime error: wrong type.
s.getColWidth(c).* = new_col_width; // Yes!
s.col_width[@backingInt(r)] // Possible, but very intentional.
s.col_width[57] // Possible, but discouraged by
// convention given by Sheet decls
// and documentation.
通用配方
为每个字段维护一个索引类型和一个访问器很笨拙。我们可以用一点 comptime 来简化这个模式,并让这个配方更加通用,以适配任意结构体。下面是一个完整的例子。
pub const Sheet = struct {
row_height: []f32,
row_hidden: []bool,
col_width: []f32,
col_hidden: []bool,
title: []const u8,
pub const Field = enum {
row_height,
row_hidden,
col_width,
col_hidden,
};
comptime {
for (std.enums.values(Field)) |f| {
std.debug.assert(@hasField(Sheet, @tagName(f)));
}
}
pub const Kind = enum { row, col };
pub fn kindOf(f: Field) Kind {
return switch (f) {
.row_height, .row_hidden => .row,
.col_width, .col_hidden => .col,
};
}
pub fn Index(comptime k: Kind) type {
return enum(u32) {
_,
};
}
pub fn at(
s: *Sheet,
comptime f: Field,
i: Index(kindOf(f)),
) *std.meta.Elem(@FieldType(Sheet, @tagName(f))) {
return &@field(s, @tagName(f))[@backingInt(i)];
}
};
让我们逐步分析。
pub const Sheet = struct {
row_height: []f32,
row_hidden: []bool,
col_width: []f32,
col_hidden: []bool,
title: []const u8,
};
我们的电子表格现在有好几个字段:一个标题,以及行和列的属性。在遍历它们时,我们有两种索引:行索引和列索引。加入类型化索引有助于防止调用者把它们混用。
pub const Field = enum {
row_height,
row_hidden,
col_width,
col_hidden,
};
这个 enum 让我们可以引用所有我们将为其构造类型化索引的结构体字段。如果所有字段都要被索引,我们会用 std.meta.FieldEnum(Sheet),但我们的电子表格有一个 title。
comptime {
for (std.enums.values(Field)) |f| {
std.debug.assert(@hasField(Sheet, @tagName(f)));
}
}
这在编译时检查每个 Field enum 变体的名字确实都是 Sheet 内部的字段。正如我们稍后会看到的,我们必须要按名字访问 Sheet 的字段,所以检查 Field 变体的名字与 Sheet 字段的名字是否匹配是件好事。
pub const Kind = enum { row, col };
这定义了我们所要构造的类型化索引的种类:一个用于行数据切片,一个用于列数据切片。Sheet 中每个被索引的字段都有一种正确的类型化索引种类。我们用一个对 Field 的穷尽 switch 来把它们对应起来。
pub fn kindOf(f: Field) Kind {
return switch(f) {
.row_height, .row_hidden => .row,
.col_width, .col_hidden => .col,
};
}
现在我们拥有了构造 .row 和 .col 两种类型化索引所需的一切。在 comptime 返回一个类型的泛型函数就是实现它的方式。
pub fn Index(comptime k: Kind) type {
return enum(u32) {
_,
};
}
行的类型化索引类型是 Sheet.Index(.row),列的是 Sheet.Index(.col)。注意 Index 函数用的是大写驼峰命名,符合 Zig 对类型的命名约定。
剩下的是提供一种使用这些类型的方式。
pub fn at(
s: *Sheet,
comptime f: Field,
i: Index(kindOf(f)),
) *std.meta.Elem(@FieldType(Sheet, @tagName(f))) {
return &@field(s, @tagName(f))[@backingInt(i)];
}
如果你不熟悉 Zig 中支持 comptime 的泛型,这部分可能看起来有点复杂,所以让我们精确地说明一下。这定义了 Sheet 上的一个方法,它要求 f 是一个在编译时已知的 Field 实例。这允许在编译时同时推断出 i 的类型和返回类型。
(原文较长,此处译出前 6000 字,完整内容请点「打开原文」。)
正文由 探How 从来源站点 RSS 同步,内容未经改写;遇到排版缺失或需要图片、视频时请以原文为准。
