Home >Backend Development >Golang >How do you programmatically list the method names defined in a Go interface?
In Go, interfaces define a contract of methods that a type must implement. When interacting with interfaces at runtime, you may need to access the names of their methods.
Problem:
Consider the following interface definition:
type FooService interface { Foo1(x int) int Foo2(x string) string }
How can you programmatically generate a list of the method names, i.e., ["Foo1", "Foo2"], from the FooService interface?
Answer:
To retrieve the list of method names from an interface type, you can use runtime reflection:
<code class="go">t := reflect.TypeOf((*FooService)(nil)).Elem() var s []string for i := 0; i < t.NumMethod(); i++ { s = append(s, t.Method(i).Name) }</code>
Explanation:
Playground Example:
https://go.dev/play/p/6cXnZKiKVw1
Tip:
Refer to the documentation on "How to get the reflect.Type of an interface?" for insights on obtaining the reflect.Type of an interface.
The above is the detailed content of How do you programmatically list the method names defined in a Go interface?. For more information, please follow other related articles on the PHP Chinese website!