给定一个函数,是否可能获取其名称?例如:
func foo() {
}
func GetFunctionName(i interface{}) string {
// ...
}
func main() {
// Will print "name: foo"
fmt.Println("name:", GetFunctionName(foo))
}
有人告诉我可以使用runtime.FuncForPC函数,但是我不太明白如何使用它。
给定一个函数,是否可能获取其名称?例如:
func foo() {
}
func GetFunctionName(i interface{}) string {
// ...
}
func main() {
// Will print "name: foo"
fmt.Println("name:", GetFunctionName(foo))
}
有人告诉我可以使用runtime.FuncForPC函数,但是我不太明白如何使用它。
package main
import (
"fmt"
"reflect"
"runtime"
)
func foo() {
}
func GetFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func main() {
// This will print "name: main.foo"
fmt.Println("name:", GetFunctionName(foo))
}
这不完全是您想要的,因为它记录了文件名和行号,但以下是我在我的Tideland Common Go库(http://tideland-cgl.googlecode.com/)中使用"runtime"包的方法:
// Debug prints a debug information to the log with file and line.
func Debug(format string, a ...interface{}) {
_, file, line, _ := runtime.Caller(1)
info := fmt.Sprintf(format, a...)
log.Printf("[cgl] debug %s:%d %v", file, line, info)
package main
import (
"reflect"
"runtime"
"strings"
)
func GetFunctionName(temp interface{}) string {
strs := strings.Split((runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name()), ".")
return strs[len(strs)-1]
}
以下是使用示例:
package main
import "fmt"
func main() {
fmt.Println(GetFunctionName(main))
}
以下是您应该期望得到的答案:
main
fmt.Println("main")
。 - Gostegaimport (
"os"
"runtime"
)
func currentFunction() string {
counter, _, _, success := runtime.Caller(1)
if !success {
println("functionName: runtime.Caller: failed")
os.Exit(1)
}
return runtime.FuncForPC(counter).Name()
}
GetFunctionName
可能会为不同的函数返回相同的名称? - jochen