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 phython如何实现以下功能?查找同一用户名的消费金额合并—
  • ¥15 孟德尔随机化怎样画共定位分析图
  • ¥18 模拟电路问题解答有偿速度
  • ¥15 CST仿真别人的模型结果仿真结果S参数完全不对
  • ¥15 误删注册表文件致win10无法开启
  • ¥15 请问在阿里云服务器中怎么利用数据库制作网站
  • ¥60 ESP32怎么烧录自启动程序
  • ¥50 html2canvas超出滚动条不显示
  • ¥15 java业务性能问题求解(sql,业务设计相关)
  • ¥15 52810 尾椎c三个a 写蓝牙地址