Iterating Over Array Fields Of A Struct

Hello,

I have a question that I have been stuck on most of the day. Luckily, I found a way around the problem but now I am even more curious about the problem as I cannot find a solution.

Say I have a struct like:
type asset struct {
hostname string
domain []string
ipaddr []string
}

Then say I have an array of those structs. Today I was trying to find a way to iterate over the ipaddr field array within a loop and did not understand how to do it. I know someone else had a somewhat similar problem that was posted here and they solved the problem using a map with interface, such as:

v := reflect.Valueof(asset)

values = make([]interface(), v.ipaddr())

for i := 0; i < v.Field(i); i++ {
values[i] = v.Field(i).Interface()
}

However, I really do not understand it and was wondering if someone could point me to some good examples out there on the net, documentation, or maybe can just try to explain it in simple terms.

Many thanks,

Joe

2 Likes

You can not use introspection on in published fields.

But I don’t really understand why are you doing introspection at all? Why not just access the fields?

2 Likes

Hi, Joe, when you have an array of structs and you want to iterate over that array and then iterate over an array nested within that struct, you need two layers of loops:

for _, asset := range assets {
    for _, ip := range asset.ipaddr {
        // do something with ip
    }
}

I see that you then tried using reflection to do this. Reflection won’t work here because the ipaddr member field is not exported, so the reflect package can’t see it, just like any other package can’t see it.

2 Likes

Skillian,

Many thanks for the snippet. It makes a lot of sense broken out in a simple manner like that.

Thanks again,
Joe

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.