如何檢查函數參數和類型 (How to inspect function arguments and types)


問題描述

如何檢查函數參數和類型 (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>

Run it on the playground.

(by Damianuser12258482)

參考文件

  1. How to inspect function arguments and types (CC BY‑SA 2.5/3.0/4.0)

#return #parameters #types #GO






相關問題

如果評估的最後一個語句是 If 語句,Ruby 會返回什麼 (What is Returned in Ruby if the Last Statement Evaluated is an If Statement)

將多個參數傳遞給 javascript 並根據兩個參數 + php 循環更新 html 內容 (pass multiple parameters to a javascript and update html content bases on both parameters + php loop)

Loại Không khớp không thể chuyển đổi từ Boolean sang Int (Mảng trong phương thức tùy chỉnh) (Type Mismatch can't convert from Boolean to Int (Arrays in custom method))

C++返回一個帶有私有構造函數的類實例 (C++ return a class instance with private constructor)

ArrayList.isEmpty() 時如何返回值? (How do I return a value when ArrayList.isEmpty()?)

如何將坐標(元組)格式化為字符串? (How can I format a coordinate (tuple) as a string?)

void 類型方法表達式體成員允許非 void 類型的表達式 *如果其他方法* (Void-type method expression-bodied member allows expression of non-void type *if other method*)

paypal動態退貨地址 (paypal dynamic return address)

讓兩個類進行交互 (getting two classes to interact)

在 C++ 中返回“this”? (return "this" in C++?)

Java:枚舉的不同返回類型 (Java: Different return type by enum)

如何檢查函數參數和類型 (How to inspect function arguments and types)







留言討論