How to dump methods of structs in Golang?

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

Leave a Comment