Getting a List of Method Names from an Interface
In Go, reflection allows for inspecting and manipulating the internal structure of a program at runtime. This includes the ability to access information about an interface type, such as its method names.
Consider the following interface:
<code class="go">type FooService interface { Foo1(x int) int Foo2(x string) string }</code>
To obtain a list of the method names for this interface using reflection:
<code class="go">t := reflect.TypeOf((*FooService)(nil)).Elem()</code>
This line retrieves the reflect.Type for the concrete type that implements the FooService interface.
<code class="go">for i := 0; i < t.NumMethod(); i++ {</code>
The NumMethod() function returns the number of methods in the interface.
<code class="go">s = append(s, t.Method(i).Name)</code>
The Method(i) function returns a reflect.Method object representing the method at index i. The Name field of this object contains the name of the method.
The resulting list s will contain the method names ["Foo1", "Foo2"].
Explanations:
The above is the detailed content of How do you retrieve a list of method names from an interface in Go using reflection?. For more information, please follow other related articles on the PHP Chinese website!