如何在 Go 中获取函数的名称?

给定一个函数,是否可以得到它的名称? 比如:

func foo() {
}


func GetFunctionName(i interface{}) string {
// ...
}


func main() {
// Will print "name: foo"
fmt.Println("name:", GetFunctionName(foo))
}

我被告知 运行时会有帮助,但我不知道如何使用它。

78280 次浏览

不完全是你想要的,因为它记录文件名和行号,但这里是我如何做到这一点在我的潮汐公共去库(http://tideland-cgl.googlecode.com/)使用“运行时”包:

// 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 (
"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))
}

通过获得 前一位听众函数名:

import (
"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()
}

我找到了一个更好的解决方案在下面这个函数中你只需要简单地传递一个函数就可以得到简单直接的输出。

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