structs icon indicating copy to clipboard operation
structs copied to clipboard

Range over nested slice of structs (using fields)

Open kurtmaile opened this issue 8 years ago • 3 comments

Hi,

I would like some help on how to iterate of the slice of structs like below. Im actually creating a recursive function that essentially walks the try down to primitives and their values. Ive covered all relect types except for handling the slice and how to use / convert a field (e.g E below), that is of stype slice (or array), and get access to the slices indexes instances and their X.Y and X.Z values?

A {
   B {
      C string
      D bool
   }
   E []*X
}

X {
   Y string
   Z int
}

I start by using

structs.New()

on an instance of the root struct, and then range over the fields as below.

for _, f := range struct.Fields() {

Its when one of the fields (kind) is a slice what do I do now to get / range over the slice indexes and their fields? I get a panic add this as the input to structs.New() again as its NOT a struct.

Im not sure how best to proceed handling the slice / array? Ive been looking at the tests but maybe missing something obvious?

Thoughts / helps much welcome

Kurt

kurtmaile avatar Apr 18 '18 13:04 kurtmaile

Help please urgent! :) Appreciated.

kurtmaile avatar Apr 19 '18 07:04 kurtmaile

From the sound of it, you most likely are using the wrong tool for the job. You most likely want to use the reflect package directly. There are many good articles online for doing this sort of thing (like this).

Outside of that, I am not sure you will accomplish what you want with this library. However, if struct B is a known type, you can do something like the following:


type B struct {
  C string
  D int
} 

s := structs.New(&A{})
a := s.Field("A")
av := a.Value()
if b, ok := av.(B); ok {
  //do something with b.  Internally, Go is using the reflection package in the type cast
  fmt.Println("B.C = ", b.C)
}

npotts avatar Oct 03 '18 21:10 npotts

Hi,

Unfortunately, I'm archiving this project and will no longer maintaining it. For more information, please read my blog post: Taking an indefinite sabbatical from my projects.

Thanks for the feedback and contribution.

fatih avatar Oct 10 '18 23:10 fatih