Golang" fmt "包中有一个名为dump的方法Printf("%+v", anyStruct)
.我正在寻找任何方法来转储结构及其方法.
例如:
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
Run Code Online (Sandbox Code Playgroud)
我想Bar()
在初始化类型实例Foo
(不仅是属性)中检查方法是否存在.
有什么好办法吗?
Jam*_*dge 33
您可以使用该reflect
包列出类型的方法.例如:
fooType := reflect.TypeOf(Foo{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
Run Code Online (Sandbox Code Playgroud)
你可以在这里玩这个:http://play.golang.org/p/wNuwVJM6vr
考虑到这一点,如果要检查类型是否实现某个方法集,您可能会发现使用接口和类型断言更容易.例如:
func implementsBar(v interface{}) bool {
type Barer interface {
Bar() string
}
_, ok := v.(Barer)
return ok
}
...
fmt.Println("Foo implements the Bar method:", implementsBar(Foo{}))
Run Code Online (Sandbox Code Playgroud)
或者,如果您只想要特定类型具有方法的编译时断言,则可以在以下某处包含以下内容:
var _ Barer = Foo{}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
12297 次 |
最近记录: |