douye2036 2016-02-04 22:34
浏览 124
已采纳

是否可以获取有关Golang中调用者函数的信息?

Is it possible get information about caller function in Golang? For example if I have

func foo() {
    //Do something
}
func main() {
    foo() 
}

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)

  • 写回答

2条回答 默认 最新

  • douzhuang6321 2016-02-04 22:48
    关注

    expanding on my comment, here's some code that returns the current func's caller

    import(
        "fmt"
        "runtime"
    )
    
    func getFrame(skipFrames int) runtime.Frame {
        // We need the frame at index skipFrames+2, since we never want runtime.Callers and getFrame
        targetFrameIndex := skipFrames + 2
    
        // Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need
        programCounters := make([]uintptr, targetFrameIndex+2)
        n := runtime.Callers(0, programCounters)
    
        frame := runtime.Frame{Function: "unknown"}
        if n > 0 {
            frames := runtime.CallersFrames(programCounters[:n])
            for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {
                var frameCandidate runtime.Frame
                frameCandidate, more = frames.Next()
                if frameIndex == targetFrameIndex {
                    frame = frameCandidate
                }
            }
        }
    
        return frame
    }
    
    // MyCaller returns the caller of the function that called it :)
    func MyCaller() string {
            // Skip GetCallerFunctionName and the function to get the caller of
            return getFrame(2).Function
    }
    
    // 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()
    }
    

    For more examples: https://play.golang.org/p/cv-SpkvexuM

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮
  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误