如何在Go中获取函数的名称?

huangapple go评论78阅读模式
英文:

How to get the name of a function in Go?

问题

给定一个函数,是否可以获取它的名称?例如:

func foo() {
}

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

func main() {
    // 将打印 "name: foo"
    fmt.Println("name:", GetFunctionName(foo))
}

我被告知runtime.FuncForPC可以帮助,但我无法理解如何使用它。

英文:

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

func foo() {
}

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

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

I was told that runtime.FuncForPC would help, but I failed to understand how to use it.

答案1

得分: 257

我找到了一个解决方案:

package main

import (
    "fmt"
    "reflect"
    "runtime"
)

func foo() {
}

func GetFunctionName(i interface{}) string {
    return runtime.FuncForPC(reflect.ValueOf(i).Pointer()).Name()
}

func main() {
    // 这将打印出 "name: main.foo"
    fmt.Println("name:", GetFunctionName(foo))
}
英文:

I found a solution:

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))
}

答案2

得分: 15

不完全是你想要的,因为它记录了文件名和行号,但是这是我在我的Tideland Common Go Library(http://tideland-cgl.googlecode.com/)中使用“runtime”包的方法:

// Debug打印带有文件和行号的调试信息到日志中。
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)
}
英文:

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)

答案3

得分: 4

我找到了一个更好的解决方案,在下面的这个函数中,你只需要传递一个函数,输出就会变得简单明了。

package main

import (
	"reflect";
	"runtime";
	"strings";
)

func GetFunctionName(temp interface{}) string {
	strs := strings.Split((runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name()), ".");
	return strs[len(strs)-1]
}

这是一个使用示例:

package main

import "fmt";

func main() {
    fmt.Println(GetFunctionName(main))
}

你应该期望得到的答案是:

main
英文:

I found a better solution, in this function down here you just simply pass a function and the output is gonna be simple and straight.

package main

import (
	"reflect"
	"runtime"
	"strings"
)

func GetFunctionName(temp interface{}) string {
	strs := strings.Split((runtime.FuncForPC(reflect.ValueOf(temp).Pointer()).Name()), ".")
	return strs[len(strs)-1]
}

And this is an example of how you use this:

package main

import "fmt"

func main() {
    fmt.Println(GetFunctionName(main))
}

And this is the answer you should expect:

main

答案4

得分: 3

通过获取上一个调用者函数名

import (
    "os"
    "runtime"
)

func currentFunction() string {
    counter, _, _, success := runtime.Caller(1)

    if !success {
        println("functionName: runtime.Caller: failed")
        os.Exit(1)
    }

    return runtime.FuncForPC(counter).Name()
}
英文:

By getting the function name of the previous caller:

import (
    "os"
    "runtime"
)

func currentFunction() string {
	counter, _, _, success := runtime.Caller(1)

	if !success {
		println("functionName: runtime.Caller: failed")
		os.Exit(1)
	}

	return runtime.FuncForPC(counter).Name()
}

huangapple
  • 本文由 发表于 2011年8月14日 03:12:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/7052693.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定