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.

az5112
  • 590
  • 2
  • 11

2 Answers2

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