question.zig:16:21: error: values of type '[2]question.Data' must be comptime-known, but index value is runtime-known
const d = datas[index];
^~~~~
question.zig:4:11: note: struct requires comptime because of this field
type: type,
^~~~
question.zig:4:11: note: types are not available at runtime
If I remove the field type: type from the structure there is no error anymore.
The only way I found is to implement create like this:
Yes I should have mentioned that the index isn’t comptime know, I would like to use the array at runtime which is possible as long as there is no comptime field in the structures (like type: type field)
You call create at runtime. create accesses an element from an array with an runtime known index. This array does contain comptime-only fields (like type), but create only accesses fields, which are accessible at runtime (like value).
I’m not sure if what you are trying to do is the correct way to solve your issue (XY problem), but if you want to execute different code, depending on a runtime variable, where the only difference between the code variants is this runtime variable as a comptime value you can do:
fn create(index: usize) void {
switch (index) {
inline 0...datas.len - 1 => |i| {
// this block is compiled with every possible value of i from 0 to datas.len - 1 (both inclusive)
const d = datas[i];
// ...
_ = d;
},
else => unreachable,
}
}