問題描述
如何檢查函數參數和類型 (How to inspect function arguments and types)
我有一個變量,它的值是一個函數,我想知道該函數的參數是什麼,特別是參數的類型和返回值的類型。我可以在 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 中做到這一點?
參考解法
方法 1:
Use the reflect package to examine the type:
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)
}
</code></pre>
(by Damian、user12258482)
參考文件