回答

收藏

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

技术问答 技术问答 351 人阅读 | 0 人回复 | 2023-09-12

给出函数,有可能得到它的名字吗?
4 [8 n6 @# p$ U' x1 ^1 w7 p
    func foo() {}func GetFunctionName(i interface{}) string      / ...}func main()      / Will print "name: foo"    fmt.Println("name:",GetFunctionName(foo))}
    * Q2 M1 @" o2 k: t. Q
有人告诉我runtime.FuncForPC会有帮助,但我不知道怎么用。  c) Y( }/ S/ _; P; z
                                                                ! d* r: M3 q5 g9 `
    解决方案:                                                               
3 `0 f$ m) f/ Z$ v0 O                                                                我找到了一个解决方案:) ^8 R9 L0 w6 G6 |; x8 [$ k" L
    package mainimport  "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))}
      `, ^% c6 {" q8 x
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则