HiveBrain v1.2.0
Get Started
← Back to all entries
snippetgoCritical

How to get the name of a function in Go?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
howfunctionnametheget

Problem

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

Code Snippets

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

Context

Stack Overflow Q#7052693, score: 281

Revisions (0)

No revisions yet.