How to print function name in golang?
April 14, 2022Hi Friends 👋,
Welcome To aGuideHub! ❤️
Today, I’m going to show you how we get the function name in golang, here we will use "reflect"
and "runtime"
packages to get the function.
We have created a function that returns the function name of the passed-in parameter.
func GetFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
Let’s write a sample function and pass it in and then check what’s returning.
package main
import (
"fmt"
"reflect"
"runtime"
)
func sampleFunction() {
}
func GetFunctionName(i interface{}) string {
return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}
func main() {
// This will print "name: main.sampleFunction"
fmt.Println("name:", GetFunctionName(sampleFunction))
}
It’s returning "name: main.sampleFunction"
in golang console.
All the best 👍