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

是否可以获取有关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)

图片转代码服务由CSDN问答提供 功能建议

是否可以获取有关Golang中调用者函数的信息? 例如,如果我有

  func foo(){
 //做某事
} 
func main(){
 foo()
} 
 <  / code>  
 
 

如何从 main 调用 foo
我能够做到这一点 其他语言(例如,在C#中,我只需要使用 CallerMemberName 类属性)

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

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条)

相关推荐 更多相似问题