10

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.

2 Answers 2

17

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.

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.

1
  • Thanks. I was guessing it was not possible (or else the doc would brag about it).
    – az5112
    Feb 13, 2022 at 10:05

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.