I am trying to create a function to dynamically generate a new struct with all the input struct fields and an additional field in the output struct type.
const std = @import("std");
const builtin = std.builtin;
const Type = builtin.Type;
const print = std.debug.print;
fn generateCommand(comptime input_struct: anytype) type {
const info = @typeInfo(input_struct);
if (info != .Struct) {
@compileError("type must be a struct definition");
}
var new_fields = [_]Type.StructField{undefined} ** (info.Struct.fields.len + 1);
for (info.Struct.fields, 0..) |field, i| {
new_fields[i] = .{
.name = field.name,
.type = field.type,
.default_value = field.default_value,
.is_comptime = field.is_comptime,
.alignment = field.alignment,
};
}
new_fields[info.Struct.fields.len] = .{
.name = "simple_name",
.type = [:0]const u8,
.default_value = "",
.is_comptime = false,
.alignment = 1,
};
return @Type(.{
.Struct = .{
.layout = .auto,
.backing_integer = null,
.fields = &new_fields,
.decls = &[_]builtin.Type.Declaration{},
.is_tuple = false,
},
});
}
const Build = struct {
path: [:0]const u8,
};
pub fn main() !void {
const generated = generateCommand(Build){
.path = "",
};
print("{any}\n", .{generated});
}
Here is the output of the above code:
└─ run zig_project_02
└─ install
└─ install zig_project_02
└─ zig build-exe zig_project_02 Debug native 1 errors
src\main.zig:37:12: error: comptime dereference requires '[:0]const u8' to have a well-defined layout
return @Type(.{
^~~~~
src\main.zig:53:38: note: called from here
const generated = generateCommand(Build){
~~~~~~~~~~~~~~~^~~~~~~
referenced by:
callMain: C:\zig\lib\std\start.zig:524:32
WinStartup: C:\zig\lib\std\start.zig:363:45
remaining reference traces hidden; use '-freference-trace' to see all reference traces
error: the following command failed with 1 compilation errors:
C:\zig\zig.exe build-exe -ODebug -Mroot=C:\X\Zig\zig_project_02\src\main.zig --cache-dir C:\X\Zig\zig_project_02\.zig-cache --global-cache-dir C:\Users\a\AppData\Local\zig --name zig_project_02 --listen=-
Build Summary: 2/7 steps succeeded; 1 failed (disable with --summary none)
run transitive failure
└─ run zig_project_02 transitive failure
├─ zig build-exe zig_project_02 Debug native 1 errors
└─ install transitive failure
└─ install zig_project_02 transitive failure
└─ zig build-exe zig_project_02 Debug native (reused)
error: the following build command failed with exit code 1:
C:\X\Zig\zig_project_02\.zig-cache\o\5dd6fef7a9d5dd514a3162aaaecfed38\build.exe C:\zig\zig.exe C:\X\Zig\zig_project_02 C:\X\Zig\zig_project_02\.zig-cache C:\Users\a\AppData\Local\zig --seed 0x27a5a29b -Za3622ac6ec9178fd run