10

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?

2
  • You didn't try that code, since it doesn't compile.
    – user1804599
    Jul 13, 2015 at 7:31
  • @ rightfold: I tried it , just added more details.
    – Mohsen
    Jul 13, 2015 at 7:41

1 Answer 1

24

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.

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.