Map is not updated: map values are fixed-size arrays

Issue

I have a map inside a structure:

type Neighborhood struct {
    rebuilt map[uint32][3]uint32 // Facet index vs {neighbor0, neighbor1, neighbor2}
}

I initialize the map:

    n := &Neighborhood{
        rebuilt: make(map[uint32][3]uint32, 9348),
    }
    // Populate neighbors with default of UINT32_MAX
    for i := uint32(0); i < 9348; i++ {
        n.rebuilt[i] = [3]uint32{math.MaxUint32, math.MaxUint32, math.MaxUint32}
    }

Later the map needs to be updated, but this doesn’t work:

                nbrs0 := n.rebuilt[4]
                nbrs1 := n.rebuilt[0]
                nbrs0[2] = 0
                nbrs1[1] = 4

The map is not actually updated with the above assignment statements. What am I missing?

Solution

You need to assign arrays again to the map.

     nbrs0 := n.rebuilt[4]
     nbrs1 := n.rebuilt[0]
     nbrs0[2] = 0
     nbrs1[1] = 4
     n.rebuilt[4] = nrbs0
     n.rebuilt[0] = nrbs1

When you assign to nbrsN you make a copy of original array. Thus changes are not propagated to map and you need to explicitly update the map with new array.

Answered By – Jaroslaw

Answer Checked By – Pedro (GoLangFix Volunteer)

Leave a Reply

Your email address will not be published.