是否有可能在golang中获得有关调用者函数的信息?
问题描述:
是否有可能在golang中获取有关调用者函数的信息?例如,如果我有
Is it possible get information about caller function in golang? For example if I have
func foo() {
//Do something
}
func main() {
foo()
}
我怎样才能从 main
?
调用 foo
我可以在其他语言(例如在C#中,我只需要使用 CallerMemberName
class属性)
How can I get that foo
has been called from main
?
I'm able to this in other language (for example in C# i just need to use CallerMemberName
class attribute)
答
扩展我的评论,这里有一些代码返回当前func的调用者
expanding on my comment, here's some code that returns the current func's caller
import(
"fmt"
"runtime"
)
// MyCaller returns the caller of the function that called it :)
func MyCaller() string {
// we get the callers as uintptrs - but we just need 1
fpcs := make([]uintptr, 1)
// skip 3 levels to get to the caller of whoever called Caller()
n := runtime.Callers(3, fpcs)
if n == 0 {
return "n/a" // proper error her would be better
}
// get the info of the actual function that's in the pointer
fun := runtime.FuncForPC(fpcs[0]-1)
if fun == nil {
return "n/a"
}
// return its name
return fun.Name()
}
// foo calls MyCaller
func foo() {
fmt.Println(MyCaller())
}
// bar is what we want to see in the output - it is our "caller"
func bar() {
foo()
}
func main(){
bar()
}