Home > Article > Backend Development > How to Print the Method Set of an Interface in Go?
How to Print the Method Set of an Interface in Golang
Getting the method set of an interface in Go can be achieved through reflection. This technique allows you to inspect and interrogate the type information of variables without knowing their specific type at compile time.
Solution:
Using the reflect package, you can access the type information and methods of an interface. Here's a code snippet demonstrating how to retrieve the function names for an interface:
<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>
This code will print the following output:
Search ListSearches ClearSearches
The reflect.TypeOf() function obtains the type information of the anonymous struct that embeds the interface. Then, t.NumMethod() provides the count of methods defined by the interface, and we iterate over them using t.Method(i).Name to obtain the method names.
The above is the detailed content of How to Print the Method Set of an Interface in Go?. For more information, please follow other related articles on the PHP Chinese website!