0

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

1 Answer 1

2

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 });
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.