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

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


func foo() {

    //Do something

}

func main() {

    foo() 

}

我怎样才能得到那个foo已经被调用的main?

我可以用其他语言(例如在 C# 中,我只需要使用CallerMemberNameclass 属性)


交互式爱情
浏览 154回答 2
2回答

大话西游666

您可以runtime.Caller用于轻松检索有关呼叫者的信息:func Caller(skip int) (pc uintptr, file string, line int, ok bool)示例 #1:打印调用者文件名和行号:https : //play.golang.org/p/cdO4Z4ApHSpackage mainimport (    "fmt"    "runtime")func foo() {    _, file, no, ok := runtime.Caller(1)    if ok {        fmt.Printf("called from %s#%d\n", file, no)    }}func main() {    foo()}示例 #2:获取更多信息runtime.FuncForPC:https : //play.golang.org/p/y8mpQq2mAvpackage mainimport (    "fmt"    "runtime")func foo() {    pc, _, _, ok := runtime.Caller(1)    details := runtime.FuncForPC(pc)    if ok && details != nil {        fmt.Printf("called from %s\n", details.Name())    }}func main() {    foo()}

临摹微笑

扩展我的评论,这里有一些代码返回当前 func 的调用者import(&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "runtime")func getFrame(skipFrames int) runtime.Frame {&nbsp; &nbsp; // We need the frame at index skipFrames+2, since we never want runtime.Callers and getFrame&nbsp; &nbsp; targetFrameIndex := skipFrames + 2&nbsp; &nbsp; // Set size to targetFrameIndex+2 to ensure we have room for one more caller than we need&nbsp; &nbsp; programCounters := make([]uintptr, targetFrameIndex+2)&nbsp; &nbsp; n := runtime.Callers(0, programCounters)&nbsp; &nbsp; frame := runtime.Frame{Function: "unknown"}&nbsp; &nbsp; if n > 0 {&nbsp; &nbsp; &nbsp; &nbsp; frames := runtime.CallersFrames(programCounters[:n])&nbsp; &nbsp; &nbsp; &nbsp; for more, frameIndex := true, 0; more && frameIndex <= targetFrameIndex; frameIndex++ {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; var frameCandidate runtime.Frame&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; frameCandidate, more = frames.Next()&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if frameIndex == targetFrameIndex {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; frame = frameCandidate&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; return frame}// MyCaller returns the caller of the function that called it :)func MyCaller() string {&nbsp; &nbsp; &nbsp; &nbsp; // Skip GetCallerFunctionName and the function to get the caller of&nbsp; &nbsp; &nbsp; &nbsp; return getFrame(2).Function}// foo calls MyCallerfunc foo() {&nbsp; &nbsp; fmt.Println(MyCaller())}// bar is what we want to see in the output - it is our "caller"func bar() {&nbsp; &nbsp; foo()}func main(){&nbsp; &nbsp; bar()}更多示例:https : //play.golang.org/p/cv-SpkvexuM
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go