How to determine the method set of an interface in Golang?

前端 未结 2 871
花落未央
花落未央 2021-01-28 04:48

How would one print the method set of the following interface?

type Searcher interface {
    Search(query string) (found bool, err error)
    ListSearches() []st         


        
2条回答
  •  无人共我
    2021-01-28 05:22

    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

提交回复
热议问题