Get function name

I have function on which a function is being called and inside that function I want to get the function name:

func MyFunc() {
  CallFunc()
}

func CallFunc() {
  // I want to print MyFunc
}

Easy solution is to pass function name as parameter. But this would be manual:

CallFunc("MyFunc")

But I think there should be some way without passing function name manually. Is there a way?

Maybe using something like runtime.Stack?

func CallFunc() {
	stack := make([]byte, 512)
	runtime.Stack(stack, false)
	fmt.Println("Stack is:")
	fmt.Println(string(stack))
}

Running in the go playground this prints:

Stack is:
goroutine 1 [running]:
main.CallFunc()
	/tmp/sandbox549134487/prog.go:20 +0x45
main.MyFunc(...)
	/tmp/sandbox549134487/prog.go:15
main.main()
	/tmp/sandbox549134487/prog.go:11 +0x18

You could poke around here for more info:

And reflect may be of interest to you:

Though it does SOUND like what you are wanting is different functionality based on where CallFunc was called from. Which does sound like something it would make sense to do with a parameter.

1 Like

Dean’s suggestion is great if you’re looking for a call stack in a format that’s good for anyone familiar with Go stack traces. If you’re looking just for the calling function’s name, you can do something like this:

package main

import (
        "fmt"
        "runtime"
)

func main() {
        fmt.Println("from main:", CallerName(0))
        func2()
}

func func2() {
        fmt.Println("from func2:", CallerName(0))
        fmt.Println(CallerName(0), "called by", CallerName(1))
}

func CallerName(skip int) string {
        pc, _, _, ok := runtime.Caller(skip + 1)
        if !ok {
                return ""
        }
        f := runtime.FuncForPC(pc)
        if f == nil {
                return ""
        }
        return f.Name()
}

Note that this will contain the “fully-qualified” function name. Functions in the main package are just main.<func name>, but non-main packages will have something like the full package name (e.g. (*github.com/account/project/package.Type).Func)

2 Likes

Dang. I did not know about that. Nice!

Came here to suggest this solution as well. It can be found in the (not so) wild: appliedgo.net/what is an ad-hoc troubleshooting tool that gets the current function name this way.

(Apologies for the self-plug. ^-^)

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.