我正在 Zig 中试验 n 维数组。
const expectEqual = std.testing.expectEqual;
fn NdArray(comptime n: comptime_int, comptime shape: [n]comptime_int) type {
if (shape.len == 0) {
// zero dimensional array, return the scalar type
return u8;
} else {
return struct {
// positive dimensional array, return an array of arrays one dimension lower
data: [shape[0]]NdArray(n - 1, shape[1..].*)
};
}
}
test "NdArray test" {
const expected = struct {
data: [2]struct {
data: [6]struct {
data: [9]struct {
data: u8
}
}
}
};
expectEqual(NdArray(3, [3]comptime_int{ 2, 6, 9 }), expected);
}
但我得到一个编译错误:
11:25: error: accessing a zero length array is not allowed
data: [shape[0]]NdArray(n - 1, shape[1..].*)
^
shape
当长度为零时,我看不到编译器到达第 11 行的任何方法。编译器是否只是禁止索引shape
,因为它没有整数文字表示的长度?