1. 程式人生 > >go反射通過字串呼叫方法

go反射通過字串呼叫方法

package main
import "fmt"
import "reflect"
func MyMissionMethod(a string){
	fmt.Println("hello, world, this is my mission.")
	fmt.Printf("and this is my params: %s \n", a)
}
func CallMethod(method interface{}){
	// here method is a interface which is a type of func
	fv := reflect.ValueOf(method)
	args := []reflect.Value{reflect.ValueOf("金天")}
	fv.Call(args)
}
func main() {
	mission := MyMissionMethod
	CallMethod(mission)
}


這裡,我callMyMissionMethod這個方法,是直接以interface這個型別去call的,明白我的意思吧?這樣的話,你就有一個辦法了,比如別人給我一個字串”MyMissionMethod”,然後我要呼叫對應的方法,我可以做一個map,對應的value是mission,這個mission就是MyMissionMethod的interface型別,最後就可以呼叫之。
好了,就講到這裡吧,下一次blog講解golang裡面的多執行緒。