-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?

1
  • 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 7, 2021 at 11:11

2 Answers 2

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.

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

1
  • Thanks! =) I wish I could accept more than one answer Aug 7, 2021 at 11:04

Not the answer you're looking for? Browse other questions tagged or ask your own question.