go

Declare pointer to function whose signature is not known


I would like to declare a variable which is a pointer to a function with an unknown signature.

For example, to declare a variable which can contain a pointer to a function which can be set to log.Printf I could go:

var foo func(format string, v ...any)

...

foo = log.Printf

But this assumes the function signature is known - in C++ I would use decltype but I can't find anything similar in Go. I tried reflect but couldn't make it work.

Anyone got any ideas?


Solution

  • Use reflection with interface, that way you will be able to use any function with interface. I made some changes and tested it on playground

    package main
    
    import (
        "log"
        "reflect"
    )
    
    func main() {
        var foo any = log.Printf
        dynamicFunction(foo, "Pointer, %s!", "Test")
    }
    
    func dynamicFunction(fn any, args ...any) {
        v := reflect.ValueOf(fn)
        in := make([]reflect.Value, len(args))
    
        for i, arg := range args {
            in[i] = reflect.ValueOf(arg)
        }
    
        v.Call(in)
    }
    

    https://go.dev/play/p/fdDwDc46jbn