#how to construct struct types at compiletime?

1 messages · Page 1 of 1 (latest)

outer agate
#

I have a function that takes a tuple of types. I want to return a tuple containing values of those types (e.g. in invocation with .{i32, []const u8} passed in could return .{5, "hello"}). how could I construct such a struct in a comptime block? I can't just create a []StructField since that requires allocation and there's not a comptime allocator or anything

frail warren
#

The simplest way is std.meta.Tuple(&.{i32, []const u8});

outer agate
#

if it's in a var args would I do std.meta.Tuple(&args)?

frail warren
#

yep

#

But in general, for creating types you just do:

pub fn CreateType(num_fields: usize) type {
    var fields: [num_fields]std.builtin.Type.StructField = undefined;
    for (&fields, 0..) |*field, i| field.* = .{
        .name = std.fmt.comptimePrint("field{d}", .{i}),
        .type = i32,
        .default_value = null,
        .is_comptime = false
        .alignment = 0,
    };
    return @Type(.{ .Struct = .{
        .layout = .Auto,
        .fields = &fields,
        .decls = &.{},
        .is_tuple = false,
    } });
}