Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to dump methods of structs in Golang?

Tags:

go

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?

like image 398
otiai10 Avatar asked Jan 28 '14 05:01

otiai10


1 Answers

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{}
like image 195
James Henstridge Avatar answered Oct 23 '22 15:10

James Henstridge