英文:
Can I Printf the name of a function assigned to a variable?
问题
有没有一种方法可以打印函数的名称(该函数被分配给一个变量)?
从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.
*/
我找到了一些答案,教你如何打印被调用的函数的名称,但没有找到获取任意函数名称的字符串表示的方法。
英文:
Is there a way to Printf the name of a function [that is assigned to a variable]?
From 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.
*/
I've found answers that instruct on how to print the name of the function being called, but not to get a string representation of [the name of] an arbitrary function.
答案1
得分: 2
你可以使用reflect
包来获取函数的uintptr
,然后将其传递给runtime.FuncForPC
以获取有关函数的信息。
runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()
https://play.golang.org/p/T3pmjd6ds1i
英文:
You can use the reflect
package to get the uintptr
of the function and then pass that to runtime.FuncForPC
to get the information on the function.
runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论