reflect and iterating over the elements in a struct

3,637 views
Skip to first unread message

Johann Höchtl

unread,
Dec 29, 2012, 6:18:33 AM12/29/12
to golan...@googlegroups.com
I figured out I can iterate through the fields of a struct in this Goplay:

http://play.golang.org/p/NJXaPCJbvB

However I wonder why reflect.FieldByIndex takes a slice instead of a plain integer,
or  I missed a better way iterating over the struct fields. E.g. I expected to see a []Value slice at some point.

Rémy Oudompheng

unread,
Dec 29, 2012, 6:32:50 AM12/29/12
to Johann Höchtl, golan...@googlegroups.com
On 2012/12/29 Johann Höchtl <johann....@gmail.com>:
You seem to be looking for the Field(int) method, which takes a plain integer.
FieldByIndex([]int{1,2,3}) is meant to access x.Blah.Foo.Bar where
Blah, Foo, Bar are the 1st, 2nd, 3rd fields of their structs.

Rémy.

Johann Höchtl

unread,
Dec 29, 2012, 6:37:16 AM12/29/12
to Rémy Oudompheng, golang-nuts


Am 29.12.2012 12:32 schrieb "Rémy Oudompheng" <remyoud...@gmail.com>:
>
> On 2012/12/29 Johann Höchtl <johann....@gmail.com>:
> > I figured out I can iterate through the fields of a struct in this Goplay:
> >
> > http://play.golang.org/p/NJXaPCJbvB
> >
> > However I wonder why reflect.FieldByIndex takes a slice instead of a plain
> > integer,
> > or  I missed a better way iterating over the struct fields. E.g. I expected
> > to see a []Value slice at some point.
>
> You seem to be looking for the Field(int) method, which takes a plain integer.

Oh my, now it's obvious.

> FieldByIndex([]int{1,2,3}) is meant to access x.Blah.Foo.Bar where
> Blah, Foo, Bar are the 1st, 2nd, 3rd fields of their structs.

Powerful abstraction.
>
> Rémy.

Reply all
Reply to author
Forward
0 new messages