首页 > 解决方案 > 如何检查函数参数和类型

问题描述

我有一个变量,它的值是一个函数,我想知道该函数的参数是什么,特别是参数的类型和返回值的类型。我可以在 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 中做到这一点?

标签: gotypesparametersreturn

解决方案


使用反射包检查类型:

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)
}

在操场上运行它


推荐阅读