package main import ( "fmt" "math" "reflect" "runtime" ) func apply(op func(int, int) int, a, b int) int { p := reflect.ValueOf(op).Pointer() opName := runtime.FuncForPC(p).Name() fmt.Printf("Calling function %s with args"+"(%d,%d)", opName, a, b) return op(a, b) } func pow(a, b int) int { return int(math.Pow(float64(a), float64(b))) } func main() { fmt.Println(apply(pow, 3, 4)) }
输出:
Calling function main.pow with args(3,4)81
package main import ( "fmt" "math" "reflect" "runtime" ) func apply(op func(int, int) int, a, b int) int { p := reflect.ValueOf(op).Pointer() opName := runtime.FuncForPC(p).Name() fmt.Printf("Calling function %s with args"+"(%d,%d)", opName, a, b) return op(a, b) } func main() { fmt.Println(apply(func(a, b int) int { return int(math.Pow( float64(a), float64(b))) }, 3, 4)) }
输出:
Calling function main.main.func1 with args(3,4)81
第一个main是包名,第二main是指main函数