How to get the name of a function in Go?

前端 未结 2 1719
感情败类
感情败类 2020-12-07 08:56

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

func foo() {
}

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

func main() {
    // Will p         


        
2条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-07 09:42

    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)
    

提交回复
热议问题