Mohsen
Mohsen

Reputation: 4266

Getting method parameter names

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?

Upvotes: 12

Views: 20074

Answers (1)

icza
icza

Reputation: 417622

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

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

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.

Upvotes: 26

Related Questions