Home  >  Article  >  Backend Development  >  How do you programmatically list the method names defined in a Go interface?

How do you programmatically list the method names defined in a Go interface?

Barbara Streisand
Barbara StreisandOriginal
2024-11-03 08:51:29932browse

How do you programmatically list the method names defined in a Go interface?

Listing Method Names in an Interface Type

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:

  1. reflect.TypeOf((*FooService)(nil)).Elem() retrieves the reflect.Type of the interface.
  2. t.NumMethod() returns the number of methods in the interface.
  3. t.Method(i) retrieves the i-th method of the interface.
  4. t.Method(i).Name returns the name of the method.

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn