How to dump methods of structs in Golang?

go

Solution

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{}

Problem

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?

Original source

Related problems