这个问题在这里已经有了答案:
How to get a function's signature as string in go
(1 个回答)
1年前关闭。
我有一个变量,它的值是一个函数,我想知道该函数的参数是什么,特别是参数的类型和返回值的类型。我可以在 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 中做到这一点?
最佳答案
使用 reflect检查类型的包:
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)
}
Run it on the playground .
关于go - 如何检查函数参数和类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63102117/