arrayscompile-timezig

Accessing comptime array in runtime with for loop


I need to be able to loop through a comptime array in runtime, but since the indexes of the for-loop is calculated at runtime, I can't do that. Is there a way to do this?

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]});


Solution

  • Use inline for loop:

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