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() {

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

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


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:")

Running in the go playground this prints:

Stack is:
goroutine 1 [running]:
	/tmp/sandbox549134487/prog.go:20 +0x45
	/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 (

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

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. (*


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: 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.