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 关于#c##的问题:最近需要用CAT工具Trados进行一些开发
  • ¥15 南大pa1 小游戏没有界面,并且报了如下错误,尝试过换显卡驱动,但是好像不行
  • ¥15 没有证书,nginx怎么反向代理到只能接受https的公网网站
  • ¥50 成都蓉城足球俱乐部小程序抢票
  • ¥15 yolov7训练自己的数据集
  • ¥15 esp8266与51单片机连接问题(标签-单片机|关键词-串口)(相关搜索:51单片机|单片机|测试代码)
  • ¥15 电力市场出清matlab yalmip kkt 双层优化问题
  • ¥30 ros小车路径规划实现不了,如何解决?(操作系统-ubuntu)
  • ¥20 matlab yalmip kkt 双层优化问题
  • ¥15 如何在3D高斯飞溅的渲染的场景中获得一个可控的旋转物体