【问题标题】:Can I Printf the name of a function assigned to a variable? [duplicate]我可以打印分配给变量的函数的名称吗? [复制]
【发布时间】:2021-08-16 19:17:55
【问题描述】:

有没有办法打印一个函数的名称[分配给一个变量]?

从去游乐场:

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.
*/

我找到了有关如何打印被调用函数的名称的答案,而不是获取任意函数 [the name of] 的字符串表示形式。

【问题讨论】:

    标签: function go formatting


    【解决方案1】:

    您可以使用reflect包获取函数的uintptr,然后将其传递给runtime.FuncForPC以获取函数信息。

    runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()
    

    https://play.golang.org/p/T3pmjd6ds1i

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-28
      • 1970-01-01
      • 2012-04-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-11-01
      • 2018-10-17
      相关资源
      最近更新 更多