簡體   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