How to determine if an anytype param is a struct (container)?

As the title says, how would I determine if an anytype param is a container and therefore capable of @hasDecl?

Iā€™m not extremely familiar with it, but you can use @typeInfo builtin which returns a std.builtin.Type

The example I used to get it working for me was the start of std.fmt.format() in the standard library.

1 Like

That is correct, check that the value returned by @typeInfo (which is a tagged union) is .Struct.

2 Likes

Thank you both!

For anyone referencing this in the future

pub fn example(value: anytype) void {
    if (@typeInfo(@TypeOf(value)) == .Struct) {
        // value is a struct
    } else {
        // value is not a struct
    }
}
4 Likes

Just wanted to add that aside from an if conditional on what @typeInfo returns, you can also switch on it if you want to handle multiple types.

2 Likes