回答

收藏

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

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

给出函数,有可能得到它的名字吗?; s0 a, Q4 A) s3 C
    func foo() {}func GetFunctionName(i interface{}) string      / ...}func main()      / Will print "name: foo"    fmt.Println("name:",GetFunctionName(foo))}
    8 G0 `& Y9 T7 t& `" A3 J' j
有人告诉我runtime.FuncForPC会有帮助,但我不知道怎么用。
: Q1 r4 k/ [9 V" h, j; y                                                                % C  k2 s/ M, k5 T; @( k
    解决方案:                                                                * W+ M8 \) e3 m
                                                                我找到了一个解决方案:& W- T+ L% z- V7 q1 R
    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))}
    ( s% `; A  H7 z: b
分享到:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则