-1

For example, I want to print out the function name of every functions of some struct.

Besides I use fmt.Println at the beginning of every member function, any better way to do it?

Browny Lin
  • 2,427
  • 3
  • 28
  • 32
  • 1
    You cannot do this. (Of course you can parse the code and insert these print statements, e.g. like the cover tool does it. But probably this is not the answer you'd like to hear.) – Volker Jan 18 '16 at 08:43

1 Answers1

0
package main

import "fmt"
import "runtime"

func main() {
    pc, _, _, _ := runtime.Caller(0)
    fmt.Println("Name of function: " + runtime.FuncForPC(pc).Name())
    fmt.Println()

    // or, define a function for it
    fmt.Println("Name of function: " + funcName())
    x()
}

func funcName() string {
    pc, _, _, _ := runtime.Caller(1)
    return runtime.FuncForPC(pc).Name()
}

func x() {
    fmt.Println("Name of function: " + funcName())
    y()
}

func y() {
    fmt.Println("Name of function: " + funcName())
    z()
}
func z() {
    fmt.Println("Name of function: " + funcName())
}

Output:

Name of function: main.main

Name of function: main.main
Name of function: main.x
Name of function: main.y
Name of function: main.z

(Copyed from here )

Community
  • 1
  • 1
Justlike
  • 1,476
  • 10
  • 18
  • it still needs to write `fmt.Println("Name of function: " + funcName())` at each member function. Is there any better way to write once and run at the beginning of each member function? – Browny Lin Jan 18 '16 at 07:49
  • Sorry. I know what u want but i dont know how to do it. Maybe u dont need it infact. It will be a big cost for cpu. If u just want to debug, just add fmt each time where u want. – Justlike Jan 18 '16 at 08:53