Analyzing a function

There are a few methods of reflect.Type in the package that will return information about a function. These methods are as follows:

  • NumIn: Returns the number of input arguments of the function
  • In: Returns the selected input argument
  • IsVariadic: Tells you if the last argument of the function is variadic
  • NumOutReturns the number of output values returned by the function
  • Out: Returns the Type value of the select output

Note that all these methods will panic if the kind of reflect.Type is not Func. We can test these methods by defining a series of functions:

func Foo() {}

func Bar(a int, b string) {}

func Baz(a int, b string) (int, error) { return 0, nil }

func Qux(a int, b ...string) (int, error) { return 0, nil }

Now we can use the method from reflect.Type to obtain information about them:

func main() {
for _, f := range []interface{}{Foo, Bar, Baz, Qux} {
t := reflect.TypeOf(f)
name := runtime.FuncForPC(reflect.ValueOf(f).Pointer()).Name()
in := make([]reflect.Type, t.NumIn())
for i := range in {
in[i] = t.In(i)
}
out := make([]reflect.Type, t.NumOut())
for i := range out {
out[i] = t.Out(i)
}
fmt.Printf("%q %v %v %v ", name, in, out, t.IsVariadic())
}
}

A full example is available here: https://play.golang.org/p/LAjjhw8Et60.

In order to obtain the name of the functions, we use the runtime.FuncForPC function, which returns runtime.Func  containing methods that will expose runtime information about the function—name, file, and line. The function takes uintptr as an argument, which can be obtained with reflect.Value of the function and its Pointer method.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.143.4.181