Last Updated: February 25, 2016
·
10.72K
· becreative-germany

Fun with the reflection package to analyse any function.

https://gist.github.com/BeCreative-Germany/5259909

package main 

import (

    "fmt"
    "reflect"
    "strconv"

)

type Test struct {

}
func (t *Test) SayHello(name string, d int, s Test ) (bool)  {

    return true
}

func FuncAnalyse(m interface{}) {

        //Reflection type of the underlying data of the interface
    x := reflect.TypeOf(m)

    numIn := x.NumIn() //Count inbound parameters
    numOut := x.NumOut() //Count outbounding parameters

    fmt.Println("Method:", x.String()) 
    fmt.Println("Variadic:", x.IsVariadic()) // Used (<type> ...) ?
    fmt.Println("Package:", x.PkgPath())


    for i := 0; i < numIn; i++ {

        inV := x.In(i)
        in_Kind := inV.Kind() //func
        fmt.Printf("\nParameter IN: "+strconv.Itoa(i)+"\nKind: %v\nName: %v\n-----------",in_Kind,inV.Name())
    }
    for o := 0; o < numOut; o++ {

        returnV := x.Out(0)
        return_Kind := returnV.Kind()
        fmt.Printf("\nParameter OUT: "+strconv.Itoa(o)+"\nKind: %v\nName: %v\n",return_Kind,returnV.Name())
    }


}

func main() {

    var n *Test = &Test{}
    methodValue := n.SayHello

    FuncAnalyse(methodValue)

}

/*

Method: func(string, int, main.Test) bool
Variadic: false
Package: 

Parameter IN: 0
Kind: string
Name: string
-----------
Parameter IN: 1
Kind: int
Name: int
-----------
Parameter IN: 2
Kind: struct
Name: Test
-----------
Parameter OUT: 0
Kind: bool
Name: bool
*/