1

Supposing I have two structs. StructA, and StructB which contains an array of StructA's. How am I able to loop through a StructB and check the value of a variable in the StructA's within it?

type StructA struct {
    varA string
    varB string
    varC string
}    


type StructB struct {
    foo  []StructA
}
I159
  • 29,741
  • 31
  • 97
  • 132
  • You might want to look at this: http://stackoverflow.com/questions/18926303/iterate-through-a-struct-in-go to see another pattern. – WiredPrairie Apr 28 '17 at 10:49

1 Answers1

1

Struct is not iterable in Go. Also you want to iterate thorough a foo attribute not through a multiple StructB fields. Therefore you should iterate through a slice which is an attribute of the struct. And then just check for equation to find a desired value or determine that it is not there.

Playground:

target := "C"
a := StructB{[]StructA{StructA{"A", "B", "C"}}}
for _, i := range a.foo {
    if target == i.varA {
        fmt.Println(i.varA)
    } else if target == i.varB {
        fmt.Println(i.varB)
    } else if target == i.varC {
        fmt.Println(i.varC)
    } else {
        fmt.Println("None of above")
    }
}

Go is pretty explicit and tricks seldom give a real profit.

I159
  • 29,741
  • 31
  • 97
  • 132