Is it possible to create a comptime
function in zig that would generate a new struct type? The function would receive an array of strings and an array of types. The strings are the names of subsequent struct fields.
Asked
Active
Viewed 2,369 times
2 Answers
16
This has been implemented now as https://github.com/ziglang/zig/pull/6099
const builtin = @import("std").builtin;
const A = @Type(.{
.Struct = .{
.layout = .Auto,
.fields = &[_]builtin.TypeInfo.StructField{
.{ .name = "one", .field_type = i32, .default_value = null, .is_comptime = false, .alignment = 0 },
},
.decls = &[_]builtin.TypeInfo.Declaration{},
.is_tuple = false,
},
});
test "" {
const a: A = .{ .one = 25 };
}
The TypeInfo struct is defined here.

pfg
- 2,348
- 1
- 16
- 37
3
Partially. This has been long proposed at https://github.com/ziglang/zig/issues/383
You can only do so with fields
, not with custom decls
.

daurnimator
- 4,091
- 18
- 34
-
Thanks. I was guessing it was not possible (or else the doc would brag about it). – az5112 Feb 13 '22 at 10:05