在Golang中获取方法参数名称 [英] Getting method parameter names in Golang

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

问题描述

给定以下Go方法:

pre $ func(t * T)TMethod(data * testData)(interface {}, *错误){
...
}

我想反映参数的名称(这里是 data )。



我尝试了以下操作,但它返回结构名称(这里 testData ):

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

如何获取参数的名称?

解决方案

无法获取参数的名称一个方法或一个函数。

原因是因为名字对于调用某个方法或函数的人来说并不重要。重要的是参数的类型和顺序。



A 函数类型表示具有相同参数和结果类型的所有函数的集合。无论参数的名称如何,具有相同参数和结果类型的2个函数的类型都是相同的。以下代码打印 true

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

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

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

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





$ b如果你想创建某种框架, 命名参数(例如,将传入的API参数映射到Go函数/方法参数),您可以使用 struct ,因为使用 reflect 包可以获得指定的字段(例如 Value.FieldByName() Type.FieldByName() ),或者您可以使用 map 。看到这个相关的问题:初始化函数字段



以下是有关 golang-nuts邮寄的相关讨论列表


Given the following Go method:

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

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

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

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

How can I get the name of the parameter?

解决方案

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.

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

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

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

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

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