如何在Go中获取函数名称? [英] How to get the name of a function in Go?

查看:531
本文介绍了如何在Go中获取函数名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出一个函数,可以得到它的名字吗?说:

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

有人告诉我 runtime.FuncForPC 会有所帮助,但我听不懂使用方法.

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

推荐答案

很抱歉回答了我自己的问题,但我找到了解决方法:

Sorry for answering my own question, but 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))
}

这篇关于如何在Go中获取函数名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆