小编典典

如何获取当前函数名称

go

出于跟踪目的,我想打印出当前函数名称,例如__FUNCTION__gcc中的宏。

这样当我有一个功能

func foo () {
   trace()
}

它会自动打印出来Entering foo()...或类似的东西。


阅读 411

收藏
2020-07-02

共1个答案

小编典典

[注意:Go
1.7+建议使用runtime.CallersFrames代替runtime.FuncForPC

运行时是您的朋友在这里:

func trace() {
    pc := make([]uintptr, 10)  // at least 1 entry needed
    runtime.Callers(2, pc)
    f := runtime.FuncForPC(pc[0])
    file, line := f.FileLine(pc[0])
    fmt.Printf("%s:%d %s\n", file, line, f.Name())
}
2020-07-02