Getting method parameter names
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.