问题描述
Printf("%+v", anyStruct)
例如:
type Foo struct {道具字符串}func (f Foo)Bar() 字符串 {返回 f.Prop}
FooBar()
有什么好的办法吗?
reflect
fooType :=reflect.TypeOf(Foo{})对于我:= 0;我<fooType.NumMethod();我++ {方法 := fooType.Method(i)fmt.Println(method.Name)}
考虑到这一点,如果您想检查一个类型是否实现了某个方法集,您可能会发现使用接口和类型断言更容易.例如:
func implementsBar(v interface{}) bool {类型 Barer 接口 {Bar() 字符串}_, 好的 := v.(Barer)返回好}...fmt.Println("Foo 实现了 Bar 方法:", implementsBar(Foo{}))
或者,如果您只是想要一个特定类型具有方法的编译时断言,您可以简单地在某处包含以下内容:
var _ Barer = Foo{}
Printf("%+v", anyStruct)
For example:
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
Bar()Foo
Is there any good way to do this?
reflect
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屋!