go - 如何检查函数参数和类型
问题描述
我有一个变量,它的值是一个函数,我想知道该函数的参数是什么,特别是参数的类型和返回值的类型。我可以在 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 中做到这一点?
解决方案
使用反射包检查类型:
t := reflect.TypeOf(f) // get reflect.Type for function f.
fmt.Println(t) // prints types of arguments and results
fmt.Println("Args:")
for i := 0; i < t.NumIn(); i++ {
ti := t.In(i) // get type of i'th argument
fmt.Println("\t", ti)
}
fmt.Println("Results:")
for i := 0; i < t.NumOut(); i++ {
ti := t.Out(i) // get type of i'th result
fmt.Println("\t", ti)
}
推荐阅读
- xamarin - iOS HttpClient 崩溃
- python - 是否有任何简单的方法可以在列表中的列表中添加元素以使列表中的所有列表具有相同数量的元素?
- java - 如何在我的 android 片段中使用 echo php
- ionic4 - 如何更改离子 4 中左填充的默认全局值?
- sbt - 无法从 SBT 发布
- python - 根据鼠标按下事件更改图表条的颜色
- jquery - 如果它与当前网址匹配,则将类添加到当前链接?
- json - 如何在使用 Scala-Play Json 框架解析 Json 时获取键和值?
- qt - 在我的项目中单击运行时,我收到“无法启动程序。路径或权限错误?”
- oracle - webutil如何将word文件读入oracle表单数据块