Home >Backend Development >Golang >How to Retrieve the Method Set of an Interface in Golang?
How to Retrieve Method Set of an Interface in Golang
Determing the method set of an interface in Golang helps you obtain a list of all the methods a specific interface enforces. To achieve this, we employ the reflect package.
Method Set Extraction Using Reflection
Without prior knowledge of the implementing concrete type, you can use the following code snippet to print the method set:
<code class="go">package main import ( "fmt" "reflect" ) type Searcher interface { Search(query string) (found bool, err error) ListSearches() []string ClearSearches() (err error) } func main() { t := reflect.TypeOf(struct{ Searcher }{}) for i := 0; i < t.NumMethod(); i++ { fmt.Println(t.Method(i).Name) } }</code>
Using reflection, we obtain the reflect.Type of the anonymous struct that conforms to the interface. The NumMethod() function retrieves the total number of methods defined by the interface, and the loop iterates through each method, printing its name.
Running the code snippet will produce the following output:
Search ListSearches ClearSearches
This method set extraction technique proves useful when you need to work with interfaces dynamically without knowledge of the implementing types.
The above is the detailed content of How to Retrieve the Method Set of an Interface in Golang?. For more information, please follow other related articles on the PHP Chinese website!