Give a function:
type myFunc func(...interface{}) (interface{})
I'd like to get the type of myFunc, something like:
t := reflect.TypeOf(myFunc)
Or
t := reflect.TypeOf((*myFunc)(nil))
The only way I have found to do this is by first creating a temporary variable of myFunc and then getting the TypeOf from that.
var v myFunc
t := reflect.TypeOf(v)
Is there a better way to do this?
The simplest way to get the function type would be reflect.TypeOf(myFunc(nil))
.
package main
import (
"fmt"
"reflect"
)
type myFunc func(...interface{}) interface{}
func main() {
t := reflect.TypeOf(myFunc(nil))
// Print whether function type is variadic
fmt.Println("Variadic =", t.IsVariadic())
// Print out every input type
for i := 0; i < t.NumIn(); i++ {
fmt.Println("In", i, "=", t.In(i))
}
// Print out every output type
for i := 0; i < t.NumOut(); i++ {
fmt.Println("Out", i, "=", t.Out(i))
}
}