如何确定Golang接口的方法集? [英] How to determine the method set of an interface in Golang?

查看:93
本文介绍了如何确定Golang接口的方法集?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一个人如何打印以下界面的方法集?

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)
}

如此

Search
ListSearches
ClearSearches

被打印出来了吗? (没有实现它的具体类型的知识.)

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

推荐答案

使用反射:

t := reflect.TypeOf(new(Searcher)).Elem()
fmt.Println(t)

for i := 0; i < t.NumMethod(); i++ {
    fmt.Println(t.Method(i).Name)
}

打印:

main.Searcher
ClearSearches
ListSearches
Search

这篇关于如何确定Golang接口的方法集?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆