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

标签 go

是否可以在 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/

相关文章:

go - 使用 errgroup 在第一个错误时取消 goroutine

pointers - 在 Go 的循环中处理指针结构的正确方法是什么?

go - 如何使用神经网络建立一个基本的围棋项目?

在 Golang 中使用替换的正则表达式

mysql - 如何从 MySQL 中选择数据然后将其附加到新结构并将其转换为字节

arrays - 如何在不将所有值清零的情况下初始化长 Golang 数组?

go - 将 go embedded struct 传递给函数

go - osPathSeparator 是 rune 类型,但想用作字符串

go - 在 golang 中声明指向 channel 的指针有什么影响吗?

Golang错误处理: understanding panic