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

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

"Struct is not iterable in Go." Reflection let one to iterate over a struct fields.
@WilliamPoussier, yes it is true, but does it help when @j0ykls1cCMbTWfD1 has a single field foo and wants to iterate through it?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.