How would one print the method set of the following interface?
type Searcher interface {
Search(query string) (found bool, err error)
ListSearches() []st
Using reflection:
t := reflect.TypeOf(new(Searcher)).Elem()
fmt.Println(t)
for i := 0; i < t.NumMethod(); i++ {
fmt.Println(t.Method(i).Name)
}
Prints:
main.Searcher
ClearSearches
ListSearches
Search
reflect
package is the right tool for this.Using reflection one can get the type information of a variable without knowing the type before hand . Here is a code snippet showing how to get the function names of functions defined as needed by an interface
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)
}
}
Check the golangplayground