代码之家  ›  专栏  ›  技术社区  ›  maja

获取调用函数的名称和包

go
  •  -3
  • maja  · 技术社区  · 7 年前

    我需要知道go包的名称和调用函数的函数(包括接收方名称)。

    这是我当前的代码:

    func retrieveCallInfo() {
        pc, _, _, _ := runtime.Caller(1)
    
        funcName := runtime.FuncForPC(pc).Name()
        lastDot := strings.LastIndexByte(funcName, '.')
    
        fmt.Printf("  Package: %s\n", funcName[:lastDot])
        fmt.Printf("  Func:   %s\n", funcName[lastDot+1:])
    }
    

    但是,代码的行为并不完全符合它的要求。

    // 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>
    

    从接收方函数调用时,接收方名称是包名称的一部分,而不是函数名称-这不是我想要的。

    下面是一个演示: https://play.golang.org/p/-99sZXr4ptD

    在第二个示例中,我希望包名 main empty.f .

    因此 runtime.FuncForPC() 是模棱两可的,还不够。

    如何得到正确的结果?

    1 回复  |  直到 7 年前
        1
  •  3
  •   maja    7 年前

    结果是正确的。你需要做一些解析来格式化你想要的结果;例如,尝试在点上拆分 在最后一个斜杠之后 在字符串中:

    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\n", funcName[:lastDot])
    fmt.Printf("Func:   %s\n", funcName[lastDot+1:])
    

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