Last active
December 15, 2015 12:19
-
-
Save StarpTech/5259909 to your computer and use it in GitHub Desktop.
Fun with the reflection package to analyse any function.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment