Skip to content
This repository has been archived by the owner on Oct 11, 2018. It is now read-only.

Range over nested slice of structs (using fields) #113

Closed
kurtmaile opened this issue Apr 18, 2018 · 3 comments
Closed

Range over nested slice of structs (using fields) #113

kurtmaile opened this issue Apr 18, 2018 · 3 comments
Labels

Comments

@kurtmaile
Copy link

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
Copy link
Author

Help please urgent! :) Appreciated.

@npotts
Copy link

npotts commented Oct 3, 2018

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

@fatih fatih added the archived label Oct 10, 2018
@fatih
Copy link
Owner

fatih commented Oct 10, 2018

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 fatih closed this as completed Oct 10, 2018
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

3 participants