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

拥有回忆 提交于 2020-11-29 23:57:36

问题


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

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

Such that

Search
ListSearches
ClearSearches

is printed out? (Without knowledge of a concrete type which implements it).


回答1:


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




回答2:


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


来源:https://stackoverflow.com/questions/38798594/how-to-determine-the-method-set-of-an-interface-in-golang

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!