Comptime: recursively visit struct elements

Hello,

I am a newbie just getting my feet wet in Zig waters, so I may be missing something obvious here. After some searching I got the following code (keep getting same results for several searches):

pub fn main() !void {
    const T = struct {
        aaa: []const u8,
        zzzz: u32 = 100,
        nested: struct {
            x: u32,
            y: u32,
        },
    };

    const t = T{
        .aaa = "hello",
        .zzzz = 200,
        .nested = .{
            .x = 10,
            .y = 20,
        },
    };
    printFieldsRecursive(T, t);
}

fn printFieldsRecursive(comptime T: type, value: T) void {
    std.debug.print("Its a struct: {}\n", .{@TypeOf(T)});
    inline for (std.meta.fields(T)) |f| {
        std.debug.print("{s}: {any}\n", .{ f.name, @field(value, f.name) });
        std.debug.print("{s}: {any}\n", .{ f.name, f.type });
        std.debug.print("TypeOf f.type: {}\n", .{@TypeOf(f.type)});
        const t = @typeInfo(f.type);
        if (t == .Struct) {
            std.debug.print("Its a struct", .{});
        }
    }
}

I cannot seem to be able to check if a field is a of a struct type. In the code above I get the error:

src/example_6.zig:70:19: error: no field named 'Struct' in enum '@typeInfo(builtin.Type).@"union".tag_type.?'
        if (t == .Struct) {
                 ~^~~~~~
/home/hmf/.config/Code/User/globalStorage/ziglang.vscode-zig/zig/linux-x86_64-0.15.0-dev.369+1a2ceb36c/lib/std/builtin.zig:568:18: note: enum declared here
pub const Type = union(enum) {
                 ^~~~~
error: the following command failed with 1 compilation errors:

I have tried several variations but have not had success. Can anyone tell me, or point me to the information on, how to check for the type of a field?

TIA

Since std: update `std.builtin.Type` fields to follow naming conventions by mlugg · Pull Request #21225 · ziglang/zig · GitHub the union field of std.builtin.Type is named struct instead of Struct. Try to change t == .Struct to t == .@"struct".

2 Likes

Thank you the change above worked perfectly.

you should mark the topic as solved

Thanks. Marked as solved.