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.

Jonathan Hall
  • 75,165
  • 16
  • 143
  • 189
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
  • 35,176
  • 4
  • 57
  • 71