Discovering public functions via reflection

One thing you can try (if you’re just looking for a single function) is to use @hasDecl: Documentation - The Zig Programming Language

Once you find the declaration, you can reflect on the type information using a guard statement:

const MyType = struct {
    pub fn foo(x: i32, y: i32) i32 {
        return x + y;
    }
};

export fn foo() i32 {

    if (comptime @hasDecl(MyType, "foo")) {
        switch (@typeInfo(@TypeOf(MyType.foo))) {
            .Fn => {
                return MyType.foo(1, 2);
            },
            else => @compileError("foo isn't a function"),
        }
    } else {
        @compileError("No foo to be found");
    }
}

Edited: @field works on functions too - not just struct fields.

If you want to, you can bind your functions to comptime fields and then iterate through them using the struct fields. Here’s an example: How to iterate over struct declarations? - #3 by AndrewCodeDev

With the comptime fields approach, you can see all of your function fields and inspect them like normal. Hope that helps!

1 Like