英文:
How to dump methods of structs in Golang?
问题
Golang的"fmt"包中有一个名为Printf("%+v", anyStruct)
的转储方法。我正在寻找一种方法来转储一个结构体以及它的方法。
例如:
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
我想检查在类型为Foo
的已初始化实例中是否存在Bar()
方法(不仅仅是属性)。
有没有什么好的方法可以做到这一点?
英文:
The Golang "fmt" package has a dump method called Printf("%+v", anyStruct)
. I'm looking for any method to dump a struct and its methods too.
For example:
type Foo struct {
Prop string
}
func (f Foo)Bar() string {
return f.Prop
}
I want to check the existence of the Bar()
method in an initialized instance of type Foo
(not only properties).
Is there any good way to do this?
答案1
得分: 56
你可以使用reflect
包列出一个类型的方法。例如:
fooType := reflect.TypeOf(&Foo{})
for i := 0; i < fooType.NumMethod(); i++ {
method := fooType.Method(i)
fmt.Println(method.Name)
}
你可以在这里尝试一下:http://play.golang.org/p/wNuwVJM6vr
在此基础上,如果你想检查一个类型是否实现了某个方法集,你可以使用接口和类型断言来简化操作。例如:
func implementsBar(v interface{}) bool {
type Barer interface {
Bar() string
}
_, ok := v.(Barer)
return ok
}
...
fmt.Println("Foo实现了Bar方法:", implementsBar(Foo{}))
或者,如果你只是想在编译时断言一个特定类型是否具有这些方法,你可以简单地在某个地方包含以下代码:
var _ Barer = Foo{}
英文:
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{}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论