Skip to content

Instantly share code, notes, and snippets.

@rockybean
Created March 1, 2016 05:49
Show Gist options
  • Save rockybean/9b001314c515aa120bbf to your computer and use it in GitHub Desktop.
Save rockybean/9b001314c515aa120bbf to your computer and use it in GitHub Desktop.
go reflect method call
package main
import (
"fmt"
"reflect"
)
var funcOp = map[string]string{
"+": "Add",
"-": "Sub",
"/": "Divide",
"*": "Multiply",
}
type Calculator struct{}
func (*Calculator) Add(a int, b int) int {
return a + b
}
func (*Calculator) Sub(a int, b int) int {
return a - b
}
func (*Calculator) Divide(a int, b int) int {
return a / b
}
func (*Calculator) Multiply(a int, b int) int {
return a * b
}
func main() {
var a, b = 6, 2
c := &Calculator{}
ct := reflect.TypeOf(c)
for op, opFun := range funcOp {
if method, ok := ct.MethodByName(opFun); ok {
params := make([]reflect.Value, 3)
params[0] = reflect.ValueOf(c)
params[1] = reflect.ValueOf(a)
params[2] = reflect.ValueOf(b)
v := method.Func.Call(params)
fmt.Println(fmt.Sprintf("%d %s %d = %d", a, op, b, v[0].Int()))
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment