小编典典

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

go

给定一个函数,是否有可能得到它的名字?说:

func foo() {
}

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

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

有人告诉我runtime.FuncForPC会有所帮助,但我不明白如何使用它。


阅读 204

收藏
2021-11-23

共1个答案

小编典典

我找到了一个解决方案:

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))
}
2021-11-23