在运行时使用 for 循环访问 comptime 数组

问题描述 投票:0回答:1

我需要能够在运行时循环遍历 comptime 数组,但由于 for 循环的索引是在运行时计算的,所以我不能这样做。有办法做到这一点吗?

const std = @import("std");

const Foo = struct {
    a: i32,
    b: f64,
    c: bool,
};

pub fn main() void {
    const x = Foo{ .a = 1, .b = 2, .c = true };

    const arr: []const std.builtin.Type.StructField = std.meta.fields(@TypeOf(x));

    for (0..arr.len) |i| {
        std.log.debug("{}\n", .{arr[i]});
    }
}

error: values of type '[]const builtin.Type.StructField' must be comptime-known, but index value is runtime-known std.log.debug("{}\n", .{arr[i]});

arrays compile-time zig
1个回答
0
投票

使用

inline for
循环:

inline for (0..arr.len) |i| {
    std.log.debug("{}\n", .{arr[i]});
}

// or

inline for (arr) |field| {
    std.log.debug("{}\n", .{ field });
}
© www.soinside.com 2019 - 2024. All rights reserved.