Getting the Name of a Method Parameter
When working with Go methods, it may be desirable to obtain the name of a specific parameter. For example, for the following method:
func (t *T) TMethod(data *testData) (interface{}, *error) { ... }
wants to get the name of the parameter data. However, using the following reflection code returns the struct name testData:
reflect.ValueOf(T).MethodByName("TMethod").Type.In(0).Elem().Name()
Why can't I get the parameter name?
Actually, in Go language, there is no way to get the name of a function or method parameter. This is because, to the caller, the name of the parameter is not important. What matters is only the type and order of the parameters.
A function type represents a collection of all functions with the same parameter and result types. If two functions have the same parameter and result types, their types are the same, regardless of the names of the parameters. The following code will print true:
func f1(a int) {} func f2(b int) {} fmt.Println(reflect.TypeOf(f1) == reflect.TypeOf(f2))
It is even possible to create functions or methods that do not give their parameters names (either all or none of the names are present in the parameter or result list). The following code works:
func NamelessParams(int, string) { fmt.Println("NamelessParams called") }
Workaround
If you wish to create a named parameter framework that maps incoming API parameters to Go function/method parameters, you can Use a struct because you can get named fields using the reflect package (such as Value.FieldByName() and Type.FieldByName()), or you can use a map. See the following related question:
Initializing function fields
For details and examples, see the related article on the Google mailing list:
Is unnamed arguments true in Go exist?
The above is the detailed content of Why Can't I Get the Name of a Go Method Parameter Using Reflection?. For more information, please follow other related articles on the PHP Chinese website!