为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

Go
杨__羊羊 2022-09-19 15:00:24
我在结构中有一个地图: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地图实际上并未使用上述赋值语句进行更新。我错过了什么?
查看完整描述

2 回答

?
明月笑刀无情

TA贡献1828条经验 获得超4个赞

您需要再次将数组分配给映射。

     nbrs0 := n.rebuilt[4]
     nbrs1 := n.rebuilt[0]
     nbrs0[2] = 0
     nbrs1[1] = 4
     n.rebuilt[4] = nrbs0
     n.rebuilt[0] = nrbs1

当您分配给 您时,请制作原始数组的副本。因此,更改不会传播到 map,您需要使用新数组显式更新映射。nbrsN


查看完整回答
反对 回复 2022-09-19
?
肥皂起泡泡

TA贡献1829条经验 获得超6个赞

您需要将值重新分配给地图条目...


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


查看完整回答
反对 回复 2022-09-19
  • 2 回答
  • 0 关注
  • 139 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号