我正在尝试编写一个使用 comptime 生成结构字段名称的 Zig 程序,但是在构建项目时遇到错误。
Zig 版本:0.13.0
下面是我的代码:
const std = @import("std");
var person_field_names = generateFieldNames(Person);
fn generateFieldNames(comptime T: type) []const []const u8 {
comptime {
const typeInfo = @typeInfo(T);
switch (typeInfo) {
.Struct => |structInfo| {
const field_count = structInfo.fields.len;
var field_names: [field_count][]const u8 = undefined;
var i: usize = 0;
while (i < field_count) : (i += 1) {
const field = structInfo.fields[i];
field_names[i] = field.name;
}
return &field_names;
},
else => @compileError("Only structs are supported!"),
}
}
}
const Person = struct {
name: []const u8,
age: u8,
};
pub fn main() void {
for (person_field_names) |name| {
std.debug.print("Field name: {s}\n", .{name});
}
}
当我运行 zig build run 时,出现以下错误:
$ zig build run
run
└─ run comptime_test
└─ zig build-exe comptime_test Debug native failure
error: the following command exited with error code 3:
C:\softs\zig\zig.exe build-exe -ODebug -Mroot=C:\workspace\zig\comptime_test\src\main.zig --cache-dir C:\workspace\zig\comptime_test\zig-cache --global-cache-dir C:\Users\myhfs\AppData\Local\zig --name comptime_test --listen=-
Build Summary: 0/5 steps succeeded; 1 failed (disable with --summary none)
run transitive failure
└─ run comptime_test transitive failure
├─ zig build-exe comptime_test Debug native failure
└─ install transitive failure
└─ install comptime_test transitive failure
└─ zig build-exe comptime_test Debug native (reused)
error: the following build command failed with exit code 1:
C:\workspace\zig\comptime_test\zig-cache\o\9c79a56d0821539e91985b5f4384125d\build.exe C:\softs\zig\zig.exe C:\workspace\zig\comptime_test C:\workspace\zig\comptime_test\zig-cache C:\Users\myhfs\AppData\Local\zig --seed 0xcf452477 -Z3cc02acbdb7abbe2 run
是什么原因导致了此错误?我该如何修复它?
错误代码似乎与我处理字段名称数组的方式有关。我相信问题出在 comptime 处理或从函数返回字段名称上。
标准库有一个函数可以执行您要执行的操作:
std.meta.fieldNames
。我已设法通过替换让您的代码工作
和
我在 中看到的一个技巧
std.meta.fieldNames
。以下是其当前源代码(Zig 0.13.0),供参考: