0

I have a variable which value is a function and I'd like to know what are the parameters of that function, specifically the types of the parameters and the type of returned value. Can I retrieve that information in Go?

In Python I can use inspect.signature function to get information about a function - its parameters and the types of parameters of that functions and also the type of the returned value.

For example in Python I can do:

from inspect import signature


def a(b: int) -> str:
    return "text"


sig = signature(a)  // contains information about parameters and returned value

How to do this in Go?

Damian
  • 178
  • 11
  • 1
    That falls under the purview of the 'reflect' package https://coderwall.com/p/b5dpwq/fun-with-the-reflection-package-to-analyse-any-function. – erik258 Jul 26 '20 at 15:31

1 Answers1

2

Use the reflect package to examine the type:

t := reflect.TypeOf(f)  // get reflect.Type for function f.
fmt.Println(t)          // prints types of arguments and results

fmt.Println("Args:")
for i := 0; i < t.NumIn(); i++ {
    ti := t.In(i)       // get type of i'th argument
    fmt.Println("\t", ti) 
}
fmt.Println("Results:")
for i := 0; i < t.NumOut(); i++ {
    ti := t.Out(i)      // get type of i'th result
    fmt.Println("\t", ti)
}

Run it on the playground.