繁体   English   中英

Zig 编译器是否将具有 comptime 可变长度的 arrays 视为可能的零长度 arrays?

[英]Does the Zig compiler consider arrays with comptime variable lengths as possible zero length arrays?

我正在 Zig 中试验 n 维 arrays。

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 ,因为它没有用 integer 文字表示的长度?

更多的是扩展评论而不是答案,我认为正如tuket所说,这似乎与编译器相关。 我期待比我即将给出的解释更好的解释 =D

看起来struct子范围(如果这样的事情适用于此)在外部 scope 之前被评估。如果将shape[0]引用转移到父 scope,它似乎有效:

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 {
        var foo = shape[0];
        return struct {
        // positive dimensional array, return an array of arrays one dimension lower
            data: [foo]NdArray(n - 1, shape[1..].*)
        };
    }
}

由于您的错误将来自此递归的最后一次通过,因此另一种选择是以非递归方式重写它。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM