如何在Golang中转储结构的方法? [英] How to dump methods of structs in Golang?
问题描述
Golangfmt包含dump方法 printf(%+ v,anyStruct)
。
我正在寻找任何方法来转储结构也倾销其方法。例如
type Foo struct {
Prop字符串
}
func(f Foo) Bar()string {
return f.Prop
}
我想检查(不仅是属性)在Foo类型的初始化实例中是否存在Bar方法。
有没有什么好方法可以做到这一点?
您可以使用 reflect
包列出类型的方法。例如:
fooType:= reflect.TypeOf(Foo {})
for i:= 0;我< fooType.NumMethod(); i ++ {
method:= fooType.Method(i)
fmt.Println(method.Name)
}
你可以在这里玩弄: http://play.golang.org/p / wNuwVJM6vr
考虑到这一点,如果您想检查某个类型是否实现了某个方法集,您可能会发现使用接口和一个类型断言。例如:
func implementsBar(v interface {})bool {
类型承载接口{
Bar ()string
}
_,ok:= v。(Barer)
return ok
}
...
fmt。 Println(Foo实现Bar方法:implementsBar(Foo {}))
或者如果你只需要相当于编译时断言,即某个特定类型具有这些方法,那么您可以简单地在以下某处添加:
var _ Barer = Foo {}
Golang "fmt" package has dump method Printf("%+v", anyStruct)
.
I'm looking for any method to dump struct also dumping its methods. such as
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
I want to check (not only properties) existence of "Bar" method in initialized instance of type "Foo".
Is there any good way to do this?
You can list the methods of a type using the reflect
package. For example:
fooType := reflect.TypeOf(Foo{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
You can play around with this here: http://play.golang.org/p/wNuwVJM6vr
With that in mind, if you want to check whether a type implements a certain method set, you might find it easier to use interfaces and a type assertion. For instance:
func implementsBar(v interface{}) bool {
type Barer interface {
Bar() string
}
_, ok := v.(Barer)
return ok
}
...
fmt.Println("Foo implements the Bar method:", implementsBar(Foo{}))
Or if you just want what amounts to a compile time assertion that a particular type has the methods, you could simply include the following somewhere:
var _ Barer = Foo{}
这篇关于如何在Golang中转储结构的方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!