【问题标题】:Map is not updated: map values are fixed-size arrays [duplicate]地图未更新:地图值是固定大小的数组[重复]
【发布时间】:2021-08-07 10:43:51
【问题描述】:

我有一个结构内的地图:

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

地图没有实际上是用上面的赋值语句更新的。我错过了什么?

【问题讨论】:

  • 你需要重新赋值,或者使用指针改变指向的值。或者使用另一种已经包含指针的类型(切片)。

标签: go


【解决方案1】:

您需要再次将数组分配给地图。

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

当您分配给nbrsN 时,您会复制原始数组。因此更改不会传播到地图,您需要使用新数组显式更新地图。

【讨论】:

    【解决方案2】:

    您需要将值分配回映射条目...

    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

    【讨论】:

    • 谢谢! =) 我希望我能接受多个答案
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-05
    • 1970-01-01
    相关资源
    最近更新 更多