如何获取当前函数名称 [英] How to get the current function name

查看:85
本文介绍了如何获取当前函数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

For tracing purpose, I'd like to print out current function name, like the __FUNCTION__ macro in gcc.

所以当我有一个功能

func foo () {
   trace()
}

它将自动打印出Entering foo()...或类似的内容.

it will automatically print out Entering foo()... or something like that.

推荐答案

[注意:Go 1.7+建议使用 runtime.CallersFrames 而不是runtime.FuncForPC; 另一个答案具有更新的示例].

[Note: Go 1.7+ recommends using runtime.CallersFrames instead of runtime.FuncForPC; another answer has an updated example].

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

Package runtime is your friend here:

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())
}

这篇关于如何获取当前函数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆