猿问

如何检查函数参数和类型

我有一个变量,它的值是一个函数,我想知道该函数的参数是什么,特别是参数的类型和返回值的类型。我可以在 Go 中检索这些信息吗?


在 Python 中,我可以使用 inspect.signature 函数来获取有关函数的信息——它的参数和该函数的参数类型以及返回值的类型。


例如在 Python 中,我可以这样做:


from inspect import signature



def a(b: int) -> str:

    return "text"



sig = signature(a)  // contains information about parameters and returned value

如何在 Go 中做到这一点?


qq_花开花谢_0
浏览 143回答 1
1回答

DIEA

使用反射包检查类型:t := reflect.TypeOf(f)&nbsp; // get reflect.Type for function f.fmt.Println(t)&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; // prints types of arguments and resultsfmt.Println("Args:")for i := 0; i < t.NumIn(); i++ {&nbsp; &nbsp; ti := t.In(i)&nbsp; &nbsp; &nbsp; &nbsp;// get type of i'th argument&nbsp; &nbsp; fmt.Println("\t", ti)&nbsp;}fmt.Println("Results:")for i := 0; i < t.NumOut(); i++ {&nbsp; &nbsp; ti := t.Out(i)&nbsp; &nbsp; &nbsp; // get type of i'th result&nbsp; &nbsp; fmt.Println("\t", ti)}
随时随地看视频慕课网APP

相关分类

Go
我要回答