This is a function to get the current function name.

Go: GetFuncName
1
2
3
4
5
6
7
8
9
10
11
12
13
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 ""
}

Example

Go: GetFuncName example
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package main

import (
	"fmt"
	"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 B() {
	fmt.Println(GetFuncName())
}

func main() {
	fmt.Println(GetFuncName()) // main
	// anonymous function 1
	func() {
		fmt.Println(GetFuncName()) // func1
	}()
	// anonymous function 2
	func() {
		fmt.Println(GetFuncName()) // func2
	}()

	a := func() {
		fmt.Println(GetFuncName())
	}

	a() // func3

	B() // B
}