是否可以在 Golang 中获取有关调用者函数的信息?例如,如果我有
func foo() {
//Do something
}
func main() {
foo()
}
我怎样才能知道 foo
已从 main
调用?
我可以用其他语言做到这一点(例如在 C# 中我只需要使用 CallerMemberName
类属性)
最佳答案
您可以使用 runtime.Caller
轻松检索有关调用者的信息:
func Caller(skip int) (pc uintptr, file string, line int, ok bool)
示例#1:打印调用者文件名和行号:https://play.golang.org/p/cdO4Z4ApHS
package main
import (
"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/y8mpQq2mAv
package main
import (
"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()
}
关于go - 是否可以在 Golang 中获取有关调用者函数的信息?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35212985/