映射未更新:映射值是固定大小的数组

我在结构中有一个地图:


type Neighborhood struct {

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

}

我初始化地图:


    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

地图实际上并未使用上述赋值语句进行更新。我错过了什么?


杨__羊羊
浏览 140回答 2
2回答

明月笑刀无情

您需要再次将数组分配给映射。&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbrs0&nbsp;:=&nbsp;n.rebuilt[4] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbrs1&nbsp;:=&nbsp;n.rebuilt[0] &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbrs0[2]&nbsp;=&nbsp;0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;nbrs1[1]&nbsp;=&nbsp;4 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;n.rebuilt[4]&nbsp;=&nbsp;nrbs0 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;n.rebuilt[0]&nbsp;=&nbsp;nrbs1当您分配给 您时,请制作原始数组的副本。因此,更改不会传播到 map,您需要使用新数组显式更新映射。nbrsN

肥皂起泡泡

您需要将值重新分配给地图条目...package mainimport (&nbsp; &nbsp; "fmt"&nbsp; &nbsp; "math")type Neighborhood struct {&nbsp; &nbsp; rebuilt map[uint32][3]uint32 // Facet index vs {neighbor0, neighbor1, neighbor2}}func main() {&nbsp; &nbsp; n := &Neighborhood{&nbsp; &nbsp; &nbsp; &nbsp; rebuilt: make(map[uint32][3]uint32, 9348),&nbsp; &nbsp; }&nbsp; &nbsp; // Populate neighbors with default of UINT32_MAX&nbsp; &nbsp; for i := uint32(0); i < 3; i++ {&nbsp; &nbsp; &nbsp; &nbsp; n.rebuilt[i] = [3]uint32{math.MaxUint32, math.MaxUint32, math.MaxUint32}&nbsp; &nbsp; }&nbsp; &nbsp; v := n.rebuilt[1]&nbsp; &nbsp; v[1] = uint32(0)&nbsp; &nbsp; fmt.Printf("%v\n", v)&nbsp; &nbsp; fmt.Printf("%v\n", n)&nbsp; &nbsp; n.rebuilt[1] = v&nbsp; &nbsp; fmt.Printf("%v\n", n)}https://play.golang.org/p/Hk5PRZlHUYc
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Go