How to list out the method name in an interface type?

依然范特西╮ 提交于 2020-04-08 18:04:53

问题


For example,

type FooService interface {
    Foo1(x int) int
    Foo2(x string) string
}

What I am attempting to do is getting list ["Foo1", "Foo2"] using runtime reflection.


回答1:


Try this:

t := reflect.TypeOf((*FooService)(nil)).Elem()
var s []string
for i := 0; i < t.NumMethod(); i++ {
    s = append(s, t.Method(i).Name)
}

playground example

Getting the reflect.Type for the interface type is the tricky part. See How to get the reflect.Type of an interface? for an explanation.



来源:https://stackoverflow.com/questions/45071659/how-to-list-out-the-method-name-in-an-interface-type

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