是否可以在 Golang 中获取有关调用者函数的信息? [英] Is it possible get information about caller function in Golang?
本文介绍了是否可以在 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
这篇关于是否可以在 Golang 中获取有关调用者函数的信息?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文