How to get the name of a function in Go?

moraes picture moraes · Aug 13, 2011 · Viewed 49.7k times · Source

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.

Answer

moraes picture moraes · Aug 14, 2011

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