英文:
Map is not updated: map values are fixed-size arrays
问题
我有一个包含在结构体中的地图:
type Neighborhood struct {
rebuilt map[uint32][3]uint32 // 面索引 vs {邻居0,邻居1,邻居2}
}
我初始化这个地图:
n := &Neighborhood{
rebuilt: make(map[uint32][3]uint32, 9348),
}
// 用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
上述赋值语句实际上没有更新地图。我漏掉了什么?
英文:
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
得分: 1
你需要重新将数组分配给地图。
nbrs0 := n.rebuilt[4]
nbrs1 := n.rebuilt[0]
nbrs0[2] = 0
nbrs1[1] = 4
n.rebuilt[4] = nbrs0
n.rebuilt[0] = nbrs1
当你将值赋给 nbrsN
时,你实际上是在复制原始数组。因此,更改不会传播到地图中,你需要显式地使用新数组更新地图。
英文:
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.
答案2
得分: 1
你需要将值分配回映射条目...
package main
import (
"fmt"
"math"
)
type Neighborhood struct {
rebuilt map[uint32][3]uint32 // 面索引 vs {邻居0,邻居1,邻居2}
}
func main() {
n := &Neighborhood{
rebuilt: make(map[uint32][3]uint32, 9348),
}
// 使用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
英文:
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)
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论