I'm experimenting with n-dimensional arrays in Zig.
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);
}
But I get a compile error:
11:25: error: accessing a zero length array is not allowed
data: [shape[0]]NdArray(n - 1, shape[1..].*)
^
I don't see any way for the compiler to reach line 11, when shape
has zero length. Does the compiler just forbid indexing of shape
, because it doesn't have length expressed by an integer literal?