是否有可能在golang中获得有关调用者函数的信息? [英] Is it possible get information about caller function in golang?

查看:449
本文介绍了是否有可能在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()
}

这篇关于是否有可能在golang中获得有关调用者函数的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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