关于如何通过反射获取函数名称

反射的包名:reflect

步骤:

1:根据传入函数获取函数的指针

2:通过指针获取函数名称

代码:

func apply(op func(int , int) int , a,b int) int{
    pointer:= reflect.ValueOf(op).Pointer()
    funcName := runtime.FuncForPC(pointer).Name()
    fmt.Printf("the runing  func name is %s  , args is (%d , %d)" , funcName , a , b)
    return op(a , b)
}

func multiplication(a,b int)int{
    return  a*b
}
func main() {
    fmt.Println(apply(multiplication , 3, 4))
}

猜你喜欢

转载自www.cnblogs.com/niutao/p/10702128.html