How to get the name of a function in Go?

前端 未结 2 1717
感情败类
感情败类 2020-12-07 08:56

Given a function, is it possible to get its name? Say:

func foo() {
}

func GetFunctionName(i interface{}) string {
    // ...
}

func main() {
    // Will p         


        
相关标签:
2条回答
  • 2020-12-07 09:26

    Sorry for answering my own question, but I found a solution:

    package main
    
    import (
        "fmt"
        "reflect"
        "runtime"
    )
    
    func foo() {
    }
    
    func GetFunctionName(i interface{}) string {
        return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
    }
    
    func main() {
        // This will print "name: main.foo"
        fmt.Println("name:", GetFunctionName(foo))
    }
    
    0 讨论(0)
  • 2020-12-07 09:42

    Not exactly what you want, because it logs the filename and the line number, but here is how I do it in my Tideland Common Go Library (http://tideland-cgl.googlecode.com/) using the "runtime" package:

    // Debug prints a debug information to the log with file and line.
    func Debug(format string, a ...interface{}) {
        _, file, line, _ := runtime.Caller(1)
        info := fmt.Sprintf(format, a...)
    
        log.Printf("[cgl] debug %s:%d %v", file, line, info)
    
    0 讨论(0)
提交回复
热议问题