How to Get the Name of a Function in Go

Created
Modified

Using runtime.FuncForPC Function

The runtime.FuncForPC() function returns a *Func describing the function that contains the given program counter address, or else nil.

See the following example:

package main

import (
  "fmt"
  "runtime"
)

func Debug() {
  if counter, _, _, ok := runtime.Caller(1); ok {
    name := runtime.FuncForPC(counter).Name()
    fmt.Println(name)
  }

}

func main() {
  Debug()
}
main.main

Related Tags

#get# #name#