0

Is there a way to Printf the name of a function [that is assigned to a variable]?

From Go Playground:

func hello(name string) string {
    return fmt.Sprintf("Hello, %s", name)
}

func main() {
    testFunc := hello
    fmt.Println(testFunc("DoubleNNs"))
    fmt.Printf("%v", testFunc)
}

/*
Output:
./prog.go:14:2: Printf format %v arg testFunc is a func value, not called
Go vet exited.

Hello, DoubleNNs
0x499200
Program exited.
*/

I've found answers that instruct on how to print the name of the function being called, but not to get a string representation of [the name of] an arbitrary function.

Flimzy
  • 68,325
  • 15
  • 126
  • 165
DoubleNNs
  • 13
  • 1

1 Answers1

2

You can use the reflect package to get the uintptr of the function and then pass that to runtime.FuncForPC to get the information on the function.

runtime.FuncForPC(reflect.ValueOf(testFunc).Pointer()).Name()

https://play.golang.org/p/T3pmjd6ds1i

mkopriva
  • 28,154
  • 3
  • 45
  • 61