GolangWebDev
GolangWebDev
1482 0 0

Get current Func and Interface name in Go

There are two useful functions in go.

Get current Func name.

func GetFuncName() string {
	pc, _, _, ok := runtime.Caller(1)
	details := runtime.FuncForPC(pc)
	if ok && details != nil {
		name := details.Name()
		index := strings.LastIndex(name, ".")
		if index >= 0 {
			return name[index+1:]
		}
		return name
	}
	return ""
}

Get any Interface name.

func GetInterfaceName(temp interface{}) string {
	funcDesc := runtime.FuncForPC(reflect.ValueOf(temp).Pointer())
	name := funcDesc.Name()
	index := strings.LastIndex(name, ".")
	if index >= 0 {
		name = name[index+1:]
	}
	if name[len(name)-3:] == "-fm" {
		name = name[:len(name)-3]
	}
	return name
}

All in one

package main

import (
	"fmt"
	"reflect"
	"runtime"
	"strings"
)

func GetFuncName() string {
	pc, _, _, ok := runtime.Caller(1)
	details := runtime.FuncForPC(pc)
	if ok && details != nil {
		name := details.Name()
		index := strings.LastIndex(name, ".")
		if index >= 0 {
			return name[index+1:]
		}
		return name
	}
	return ""
}

func GetInterfaceName(temp interface{}) string {
	fmt.Println(GetFuncName()) // GetInterfaceName
	funcDesc := runtime.FuncForPC(reflect.ValueOf(temp).Pointer())
	name := funcDesc.Name()
	index := strings.LastIndex(name, ".")
	if index >= 0 {
		name = name[index+1:]
	}
	if name[len(name)-3:] == "-fm" {
		name = name[:len(name)-3]
	}
	return name
}

func main() {
	fmt.Println(GetFuncName())                 // main
	fmt.Println(GetInterfaceName(GetFuncName)) // GetFuncName
}

Output:

main
GetInterfaceName
GetFuncName
0

See Also


Discussion

Login Topics