如何获取当前函数名 [英] How to get the current function name
本文介绍了如何获取当前函数名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
出于跟踪目的,我想打印出当前的函数名称,例如 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].
包 runtime 是您的朋友:
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
", file, line, f.Name())
}
这篇关于如何获取当前函数名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文