38

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?

Rene Knop
  • 1,788
  • 3
  • 15
  • 27
otiai10
  • 4,289
  • 5
  • 38
  • 50

1 Answers1

56

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{}
JohnAllen
  • 7,317
  • 9
  • 41
  • 65
James Henstridge
  • 42,244
  • 6
  • 132
  • 114
  • Thanks a lot!! I didn't want to use "reflect" package, so your suggestion using interface looks so cool for me! – otiai10 Jan 28 '14 at 06:09
  • 4
    To find the *T methods you have to provide a `TypeOf(&Foo{})` – BG Adrian Nov 08 '18 at 13:39
  • Thanks James and @BGAdrian, would you pls help how can I get the method interface as well? – Davood Falahati Mar 06 '20 at 20:55
  • 1
    @Davood [how to list method names in an interface](https://stackoverflow.com/questions/45071659/how-to-list-out-the-method-name-in-an-interface-type) and [how to determine a method set in an interface](https://stackoverflow.com/questions/38798594/how-to-determine-the-method-set-of-an-interface-in-golang) use reflect to do this. –  Mar 06 '20 at 22:19