获取方法参数名称 [英] Getting method parameter names

查看:108
本文介绍了获取方法参数名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下Go方法:

func (t *T) TMethod(data *testData) (interface{}, *error) {
    ...
}

我想反映参数的名称(此处为data).

I want to reflect the name of the parameter (which is data here).

我尝试了以下操作,但是它返回了结构名称(此处为testData):

I tried the following, but it returns the structure name (which is testData here):

reflect.ValueOf(T).MethodByName("TMethod").Type().In(0).Elem().Name()

如何获取参数名称?

推荐答案

无法获取方法或函数的参数名称.

There is no way to get the names of the parameters of a method or a function.

之所以这样做,是因为名称对于调用方法或函数的人来说并不重要.重要的是参数的类型及其顺序.

The reason for this is because the names are not really important for someone calling a method or a function. What matters is the types of the parameters and their order.

函数类型表示具有相同参数和结果类型的所有函数的集合.无论参数名称如何,具有相同参数和结果类型的2个函数的类型均相同.以下代码显示true:

A Function type denotes the set of all functions with the same parameter and result types. The type of 2 functions having the same parameter and result types is identical regardless of the names of the parameters. The following code prints true:

func f1(a int) {}
func f2(b int) {}

fmt.Println(reflect.TypeOf(f1) == reflect.TypeOf(f2))

甚至可以创建一个甚至不给参数命名的函数或方法(在参数或结果列表中,名称必须全部存在或全部不存在).这是有效的代码:

It is even possible to create a function or method where you don't even give names to the parameters (within a list of parameters or results, the names must either all be present or all be absent). This is valid code:

func NamelessParams(int, string) {
    fmt.Println("NamelessParams called")
}

有关详细信息和示例,请参见未命名的参数是否有用在Go中?

For details and examples, see Is unnamed arguments a thing in Go?

如果要创建某种框架,在其中调用将值传递给命名"参数的函数(例如,将传入的API参数映射到Go函数/方法参数),则可以使用 Type.FieldByName() ),也可以使用 map .请参阅以下相关问题:初始化函数字段

If you want to create some kind of framework where you call functions passing values to "named" parameters (e.g. mapping incoming API params to Go function/method params), you may use a struct because using the reflect package you can get the named fields (e.g. Value.FieldByName() and Type.FieldByName()), or you may use a map. See this related question: Initialize function fields

有关 golang-nuts邮件列表的相关讨论.

Here is a relevant discussion on the golang-nuts mailing list.

这篇关于获取方法参数名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆