I’m able to loop through struct fields only by inline for. Why is that?
const Point = struct {
x: u32,
y: u32,
};
pub fn main() !void {
const points_fields = std.meta.fields(Point);
for (points_fields) |f| {
std.debug.print(" - {s}\n", .{f.name});
}
}
const std = @import("std");
This is the error message I’m getting
error: values of type '[]const builtin.Type.StructField' must be comptime-known, but index value is runtime-known
The struct in question contains compile-time only types that cannot be represented at runtime:
pub const StructField = struct {
name: [:0]const u8,
type: type, // ← types cannot be represented at runtime
default_value_ptr: ?*const anyopaque,
is_comptime: bool,
alignment: comptime_int, // ← comptime integers, as the name suggests, cannot be represented at runtime
4 Likes
ahh it makes sense now. thank you
Sze
July 20, 2025, 8:34pm
4
You can use inline for to generate the loop body at comptime.
If you really want to do it at runtime, you could cast your structure to an array of u32, but this only works if all your fields are u32.
invlpg
July 25, 2025, 5:34pm
6
While this works now, I don’t think the language intends to guarantee field layout unless the struct is marked extern or packed in the future. Happy to be corrected on that.
To address the question in the title directly: how would your program know the offsets of the fields at runtime?
2 Likes