duancashi1362 2018-10-26 16:08
浏览 53
已采纳

获取调用函数的名称和包

I need to know the name of the go-package and function (including the receiver name) of the calling function.

This is my current code:

func retrieveCallInfo() {
    pc, _, _, _ := runtime.Caller(1)

    funcName := runtime.FuncForPC(pc).Name()
    lastDot := strings.LastIndexByte(funcName, '.')

    fmt.Printf("  Package: %s
", funcName[:lastDot])
    fmt.Printf("  Func:   %s
", funcName[lastDot+1:])
}

However, the code doesn't behave exactly as it should.

// When called from a conventional (free) function:
runtime.FuncForPC(pc).Name() // returns <package-path>.<funcName>

// When called from a method receiver function:
runtime.FuncForPC(pc).Name() // returns <package-path>.<receiverName>.<funcName>

When called from a receiver function, the receiver name is part of the package name, rather than the function name - which is not what I want.

Here's a demonstration: https://play.golang.org/p/-99sZXr4ptD

In the second example, I want the package name to be main and the function name to be empty.f. Since dots are also valid parts of a package name, I can't simply split at another dot - maybe it's actually not the receiver, but part of the package name.

Hence, the information returned by runtime.FuncForPC() is ambiguous and not enough.

How can I get the correct results?

  • 写回答

1条回答 默认 最新

  • doufu8127 2018-10-26 16:20
    关注

    The results are correct. You'll need to do some parsing to format the results the way you want them; for example, try splitting on dots after the last slash in the string:

    pc, _, _, _ := runtime.Caller(1)
    funcName := runtime.FuncForPC(pc).Name()
    lastSlash := strings.LastIndexByte(funcName, '/')
    if lastSlash < 0 {
        lastSlash = 0
    }
    lastDot := strings.LastIndexByte(funcName[lastSlash:], '.') + lastSlash
    
    fmt.Printf("Package: %s
    ", funcName[:lastDot])
    fmt.Printf("Func:   %s
    ", funcName[lastDot+1:])
    

    Playground: https://play.golang.org/p/-Nbos0a1Ifp

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 keil的map文件中Image component sizes各项意思
  • ¥30 BC260Y用MQTT向阿里云发布主题消息一直错误
  • ¥20 求个正点原子stm32f407开发版的贪吃蛇游戏
  • ¥15 划分vlan后,链路不通了?
  • ¥20 求各位懂行的人,注册表能不能看到usb使用得具体信息,干了什么,传输了什么数据
  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 Centos / PETGEM
  • ¥15 划分vlan后不通了
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)