小编典典

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

go

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

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

我怎样才能得到那个foomain
我可以使用其他语言(例如,在C#中,我只需要使用CallerMemberNameclass属性)


阅读 401

收藏
2020-07-02

共1个答案

小编典典

扩展我的评论,这是一些返回当前func调用者的代码

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

2020-07-02