我有一个变量,它的值是一个函数,我想知道该函数的参数是什么,特别是参数的类型和返回值的类型。我可以在 Go 中检索这些信息吗?在 Python 中,我可以使用 inspect.signature 函数来获取有关函数的信息——它的参数和该函数的参数类型以及返回值的类型。例如在 Python 中,我可以这样做:from inspect import signaturedef a(b: int) -> str: return "text"sig = signature(a) // contains information about parameters and returned value如何在 Go 中做到这一点?
1 回答

DIEA
TA贡献1820条经验 获得超2个赞
使用反射包检查类型:
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)
}
- 1 回答
- 0 关注
- 118 浏览
添加回答
举报
0/150
提交
取消