goreflectiongo-reflect

How to get the name of a function in Go?


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

func foo() {
}

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

func main() {
    // Will print "name: foo"
    fmt.Println("name:", GetFunctionName(foo))
}

I was told that runtime.FuncForPC would help, but I failed to understand how to use it.


Solution

  • 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))
    }