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

前端 未结 2 868
花落未央
花落未央 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:17

    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
    
    0 讨论(0)
  • 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

    0 讨论(0)
提交回复
热议问题