snippetgoCritical
How to get the name of a function in Go?
Viewed 0 times
howfunctionnametheget
Problem
Given a function, is it possible to get its name? Say:
I was told that runtime.FuncForPC would help, but I failed to understand how to use it.
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.