我在一个结构中有一个映射:
type Neighborhood struct {
rebuilt map[uint32][3]uint32 // Facet index vs {neighbor0, neighbor1, neighbor2}
}
初始化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}
}
稍后需要更新地图,但这不起作用:
nbrs0 := n.rebuilt[4]
nbrs1 := n.rebuilt[0]
nbrs0[2] = 0
nbrs1[1] = 4
映射是而不是实际上是用上面的赋值语句更新的。我错过了什么?
您需要重新为map分配数组。
nbrs0 := n.rebuilt[4]
nbrs1 := n.rebuilt[0]
nbrs0[2] = 0
nbrs1[1] = 4
n.rebuilt[4] = nrbs0
n.rebuilt[0] = nrbs1
当你赋值给nbrsN
时,你复制了原始数组。因此,更改不会传播到map,您需要显式地使用新数组更新map。
你需要赋值回映射条目…
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("%vn", v)
fmt.Printf("%vn", n)
n.rebuilt[1] = v
fmt.Printf("%vn", n)
}
https://play.golang.org/p/Hk5PRZlHUYc