如何在Go中以字符串形式获取函数的签名 [英] How to get a function's signature as string in go

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

问题描述

我正在实现一个可以加载go插件的go模块.

I'm implementing a go module that loads go plugins.

我假设主程序包中存在具有特定名称和特定签名的函数,并且如果找不到或与期望的签名不匹配,希望有一个不错的错误消息.

I'm assuming a function with a certain name and a certain signature exists on the main package, and would like to have a nice error message in case it is not found or not matching the expected signature.

给出具有函数类型的变量,如何获得该函数的基础签名?

Given a variable with a function type, how can one get the underlying signature of that function?

以下仅显示类型名称(例如 main.ModuleInitFunc ),而不显示完整签名.

The following only prints the type's name (e.g. main.ModuleInitFunc) and not the full signature.

package main

import "fmt"

type ModuleInitFunc func(someInt int) error

func main() {
    var myFunc ModuleInitFunc = nil

    fmt.Printf("%T", lol)
}

推荐答案

reflect.Type.String()仅返回类型名称,因此,如果函数值具有命名类型,您将只看到类型名称.请注意,如果函数值为函数文字(具有未命名的类型),则会打印函数的签名:

reflect.Type.String() only returns the type name, so if the function value has a named type, you'll only see the type name. Note that this will print the function's signature if the function value is a function literal (has an unnamed type):

var myFunc ModuleInitFunc

fmt.Printf("%T\n", myFunc)
fmt.Printf("%T\n", func(i int) error { return nil })

输出(在转到游乐场上尝试):

main.ModuleInitFunc
func(int) error

如果类型是命名类型,则我们必须自己构造签名,但幸运的是, reflect.Type 具有我们所需的全部信息.

If the type is a named type, we have to construct the signature ourselves, but fortunately the reflect.Type has all the information we need for that.

Type.In()返回第i个 参数的类型,类似地, Type.Out()返回该参数的类型.第 th 个结果类型.

Type.In() returns the type of the ith parameter, and similarly Type.Out() returns the type of the ith result type.

使用这些示例,下面是一个示例实现,该示例返回函数值的签名:

Using those, here's an example implementation that returns the signature of a function value:

func signature(f interface{}) string {
    t := reflect.TypeOf(f)
    if t.Kind() != reflect.Func {
        return "<not a function>"
    }

    buf := strings.Builder{}
    buf.WriteString("func (")
    for i := 0; i < t.NumIn(); i++ {
        if i > 0 {
            buf.WriteString(", ")
        }
        buf.WriteString(t.In(i).String())
    }
    buf.WriteString(")")
    if numOut := t.NumOut(); numOut > 0 {
        if numOut > 1 {
            buf.WriteString(" (")
        } else {
            buf.WriteString(" ")
        }
        for i := 0; i < t.NumOut(); i++ {
            if i > 0 {
                buf.WriteString(", ")
            }
            buf.WriteString(t.Out(i).String())
        }
        if numOut > 1 {
            buf.WriteString(")")
        }
    }

    return buf.String()
}

测试:

var myFunc ModuleInitFunc

fmt.Println(signature(func(i int) error { return nil }))
fmt.Println(signature(myFunc))
fmt.Println(signature(time.Now))
fmt.Println(signature(os.Open))
fmt.Println(signature(log.New))
fmt.Println(signature(""))

输出(在转到游乐场上尝试):

func (int) error
func (int) error
func () time.Time
func (string) (*os.File, error)
func (io.Writer, string, int) *log.Logger
<not a function>

请注意,不可能同时打印参数名称和结果类型,因为这是无法存储/访问的.有关详细信息,请参见未命名的参数在Go中是否有用?

Note that it is not possible to also print the names of the parameters and result types, because that is not stored / accessible. For details, see Is unnamed arguments a thing in Go?

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

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