121

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

func foo() {
}

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

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

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

4

4 回答 4

230

我找到了一个解决方案:

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))
}
于 2011-08-13T23:10:33.940 回答
12

不完全是您想要的,因为它记录了文件名和行号,但这是我在 Tideland 通用 Go 库 ( 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)
于 2011-08-13T21:39:06.930 回答
1

更好的解决方案

我实际上找到了一个更好的解决方案,在这个函数中,你只需简单地传递一个函数,输出就会简单直接。

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
于 2021-12-30T19:18:52.827 回答
-1

通过获取前一个调用者函数名

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()
}
于 2021-10-13T03:18:36.853 回答