How to get the name of a function in Go?

GoReflectionGo Reflect

Go Problem Overview


Given a function, is it possible to get its name? Say:

func foo() {
}

func GetFunctionName(i interface{}) string {
    // ...
}

func main() {
    // Will print "name: foo"
    fmt.Println("name:", GetFunctionName(foo))
}

I was told that runtime.FuncForPC would help, but I failed to understand how to use it.

Go Solutions


Solution 1 - Go

I found a solution:

package main

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

func foo() {
}

func GetFunctionName(i interface{}) string {
    return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func main() {
    // This will print "name: main.foo"
    fmt.Println("name:", GetFunctionName(foo))
}

Solution 2 - Go

Not exactly what you want, because it logs the filename and the line number, but here is how I do it in my Tideland Common Go Library (http://tideland-cgl.googlecode.com/) using the "runtime" package:

// Debug prints a debug information to the log with file and line.
func Debug(format string, a ...interface{}) {
    _, file, line, _ := runtime.Caller(1)
    info := fmt.Sprintf(format, a...)

    log.Printf("[cgl] debug %s:%d %v", file, line, info)

Solution 3 - Go

Better Solution

I found a better solution, in this function down here you just simply pass a function and the output is gonna be simple and straight.

package main

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

func GetFunctionName(temp interface{}) string {
	strs := strings.Split((runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name()), ".")
	return strs[len(strs)-1]
}

And this is an example of how you use this:

package main

import "fmt"

func main() {
    fmt.Println(GetFunctionName(main))
}

And this is the answer you should expect:

main

Solution 4 - Go

By getting the function name of the previous caller:

import (
    "os"
    "runtime"
)

func currentFunction() string {
	counter, _, _, success := runtime.Caller(1)

	if !success {
		println("functionName: runtime.Caller: failed")
		os.Exit(1)
	}

	return runtime.FuncForPC(counter).Name()
}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmoraesView Question on Stackoverflow
Solution 1 - GomoraesView Answer on Stackoverflow
Solution 2 - GothemueView Answer on Stackoverflow
Solution 3 - GoMahmoodView Answer on Stackoverflow
Solution 4 - GoAlberto Salvia NovellaView Answer on Stackoverflow