我可以打印分配给变量的函数名称吗?
Can I Printf the name of a function assigned to a variable?
有没有办法 Printf [分配给变量] 的函数名称?
来自 Go Playground:
func hello(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
func main() {
testFunc := hello
fmt.Println(testFunc("DoubleNNs"))
fmt.Printf("%v", testFunc)
}
/*
Output:
./prog.go:14:2: Printf format %v arg testFunc is a func value, not called
Go vet exited.
Hello, DoubleNNs
0x499200
Program exited.
*/
我找到了指示如何打印被调用函数的名称的答案,而不是获取任意函数 [的名称] 的字符串表示形式。
您可以使用reflect
package to get the uintptr
of the function and then pass that to runtime.FuncForPC
获取函数的信息。
runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()
有没有办法 Printf [分配给变量] 的函数名称?
来自 Go Playground:
func hello(name string) string {
return fmt.Sprintf("Hello, %s", name)
}
func main() {
testFunc := hello
fmt.Println(testFunc("DoubleNNs"))
fmt.Printf("%v", testFunc)
}
/*
Output:
./prog.go:14:2: Printf format %v arg testFunc is a func value, not called
Go vet exited.
Hello, DoubleNNs
0x499200
Program exited.
*/
我找到了指示如何打印被调用函数的名称的答案,而不是获取任意函数 [的名称] 的字符串表示形式。
您可以使用reflect
package to get the uintptr
of the function and then pass that to runtime.FuncForPC
获取函数的信息。
runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()