我需要能够在运行时循环遍历 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]});
inline for
循环:
inline for (0..arr.len) |i| {
std.log.debug("{}\n", .{arr[i]});
}
// or
inline for (arr) |field| {
std.log.debug("{}\n", .{ field });
}