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

问题描述:

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

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

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

我怎样才能知道 foo 已经被 main 调用了?
我可以用其他语言(例如在 C# 中,我只需要使用 CallerMemberName 类属性)

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

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()
}

更多示例:https://play.golang.org/p/cv-SpkvexuM