"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How do you retrieve a list of method names from an interface in Go using reflection?

How do you retrieve a list of method names from an interface in Go using reflection?

Published on 2024-11-11
Browse:231

How do you retrieve a list of method names from an interface in Go using reflection?

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:

type FooService interface {
    Foo1(x int) int
    Foo2(x string) string
}

To obtain a list of the method names for this interface using reflection:

  1. Obtain the reflect.Type for the interface type:
t := reflect.TypeOf((*FooService)(nil)).Elem()

This line retrieves the reflect.Type for the concrete type that implements the FooService interface.

  1. Retrieve the number of methods:
for i := 0; i 

The NumMethod() function returns the number of methods in the interface.

  1. Get the method names:
s = append(s, t.Method(i).Name)

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 (*FooService)(nil) syntax is used to create a pointer to an anonymous instance of the FooService interface. This is necessary to obtain the reflect.Type for the interface.
  • The Elem() method returns the reflect.Type for the concrete type that implements the interface, instead of the interface type itself.
  • The NumMethod() function returns the number of methods declared in the interface, even if the concrete type implements additional methods.
Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3