-2

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?

Megidd
  • 7,089
  • 6
  • 65
  • 142
  • 2
    You need to reassign values, or use pointers and change the pointed value. Or use another type (slice) which already wraps a pointer. – icza Aug 07 '21 at 11:11

2 Answers2

1

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.

Jaroslaw
  • 636
  • 3
  • 8
1

You need to assign value back to map entry...

package main

import (
    "fmt"
    "math"
)

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

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

    v := n.rebuilt[1]
    v[1] = uint32(0)
    fmt.Printf("%v\n", v)
    fmt.Printf("%v\n", n)
    n.rebuilt[1] = v
    fmt.Printf("%v\n", n)

}

https://play.golang.org/p/Hk5PRZlHUYc

Oleg Butuzov
  • 4,795
  • 2
  • 24
  • 33