So, I believe zig can't return anytype & have that type inferred - which is understandable for readability, and constructing the desired type at comptime is generally easy
However, i'm doing some pretty heavy comptime manipulation of anonymous struct data for some auto serialization library - so my types are annotated as follows:
const Foo = struct {
const serializer_config = .{
.ignore = .{"foo", "baz"}
}
foo: i32,
bar: i32,
baz: i32,
}
Then my auto-serializer function walks the type tree, reads the config attached to the type, and serializes appropriately - so in this case it reads ignore and only serializes bar
So, typically I have many functions that operate on this config type, e.g.:
fn getFieldIgnores(comptime config: anytype) ??? {
if (@hasField(@TypeOf(config), "ignore")) {
return config.ignore;
}
else {
return .{};
}
}
What is the return type of this function?
To compute the return type manually means effectively duplicating each function (and I have many functions that operate on this config anytype):
fn GetFieldIgnores(comptime config: anytype) type {
if (@hasField(@TypeOf(config), "ignore")) {
return @TypeOf(config.ignore);
}
else {
return struct{};
}
}
fn getFieldIgnores(comptime config: anytype) GetFieldIgnores(config) {
if (@hasField(@TypeOf(config), "ignore")) {
return config.ignore;
}
else {
return .{};
}
}
This gets a bit silly, though.
Is there any way around the anytype return restriction, which isn't an insane hack likely to not work between compiler versions?
Thanks 🙂