我想用 Zig 制作一个反序列化器。现在我可以在 comptime 中迭代字段信息。但我想获取 struct 中的字段默认值。有办法得到它们吗?例如,我想获取中zzzz的值。100getIntOrDefault
const std = @import("std");
const meta = std.meta;
const trait = meta.trait;
const assert = std.debug.assert;
pub fn deserializeInto(ptr: anytype) !void {
const T = @TypeOf(ptr);
comptime assert(trait.is(.Pointer)(T));
const C = comptime meta.Child(T);
ptr.* = switch (C) {
[]const u8 => "test string",
else => switch (@typeInfo(C)) {
.Struct => try deserializeStruct(C),
.Int => try getIntOrDefault(C),
else => @compileError("Unsupported deserialization type " ++ @typeName(C) ++ "\n"),
},
};
}
pub fn getIntOrDefault(comptime T: type) !T {
return 2;
}
pub fn deserializeStruct(comptime T: type) !T {
var value: T = undefined;
inline for (meta.fields(T)) |struct_field| {
try deserializeInto(&@field(value, struct_field.name));
}
return value;
}
pub fn main() !void {
const T = struct {
wwww: []const u8,
zzzz: u32 = 100,
};
var v: T = undefined;
try deserializeInto(&v);
std.debug.print("zzzz value is {d}\n", .{v.zzzz});
}
Run Code Online (Sandbox Code Playgroud)
默认值可用作@typeInfo(T).Struct.fields[...].default_value。但它存储为指向 的指针anyopaque,您将无法取消引用它,除非您@ptrCast像这样进行转换:
const std = @import("std");
pub fn main() !void {
const TestStruct = struct {
foo: u32 = 123,
};
std.log.info("{}", .{ TestStruct{} });
const foo_field = @typeInfo(TestStruct).Struct.fields[0];
std.log.info("field name: {s}", .{ foo_field.name });
if (foo_field.default_value) |dvalue| {
const dvalue_aligned: *const align(foo_field.alignment) anyopaque = @alignCast(dvalue);
const value = @as(*const foo_field.type, @ptrCast(dvalue_aligned)).*;
std.log.info("default value: {}", .{ value });
}
}
Run Code Online (Sandbox Code Playgroud)
它打印:
$ zig build run
info: main.main.TestStruct{ .foo = 123 }
info: field name: foo
info: default value: 123
Run Code Online (Sandbox Code Playgroud)
以前的用法@ptrCast是这样的:
const dvalue_aligned = @alignCast(foo_field.alignment, dvalue);
const value = @ptrCast(*const foo_field.type, dvalue_aligned).*;
std.log.info("default value: {}", .{ value });
Run Code Online (Sandbox Code Playgroud)