121

関数が与えられた場合、その名前を取得することは可能ですか? 言う:

func foo() {
}

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

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

runtime.FuncForPCが役立つと言われましたが、使い方がわかりませんでした。

4

4 に答える 4

230

私は解決策を見つけました:

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))
}
于 2011-08-13T23:10:33.940 に答える
12

ファイル名と行番号がログに記録されるため、正確には必要ありませんが、「ランタイム」パッケージを使用して、Tideland Common Go ライブラリ ( http://tideland-cgl.googlecode.com/ ) で行う方法を次に示します。

// 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)
于 2011-08-13T21:39:06.930 に答える