douxia3505 2016-04-02 03:05
浏览 52
已采纳

为什么不能在Go中分配给地图内的数组?

Here's a short example to demonstrate:

package main

import "fmt"

func main() {
    array := [3]int{1, 2, 3}
    array[0]++ // Works
    slice := make([]int, 3)
    for i := range slice {
        slice[i] = i + 1
    }
    arrayMap := make(map[int][3]int)
    sliceMap := make(map[int][]int)
    arrayMap[0] = array
    sliceMap[0] = slice
    //arrayMap[0][0]++ // Does not compile: "cannot assign to arrayMap[0][0]"
    sliceMap[0][0]++
    fmt.Println(arrayMap)
    fmt.Println(sliceMap)
}

Why can I not modify the contents of an array if it's inside a map, even though they are mutable outside the map? And why does this work with slices?

  • 写回答

1条回答 默认 最新

  • doucao1888 2016-04-02 04:08
    关注

    For maps, its values are not addressable. That is, when you use a value type (arrays are value types in Go), you cannot address the value using ++.

    But, if you use a reference type (slices are reference types in Go), you can as you already alluded to in the example.

    This holds true regardless of type used in the Map.

    One thing we can do instead is to use the ptr address of the type. For example, if you take the address of the array, then it should work:

    Playground: http://play.golang.org/p/XeIThVewWD

    package main
    
    import "fmt"
    
    func main() {
        array := [3]int{1, 2, 3}
        slice := []int{1, 2, 3}
    
        arrayMap := make(map[int]*[3]int) // use the pointer to the type
        sliceMap := make(map[int][]int)
        arrayMap[0] = &array // get the pointer to the type
        sliceMap[0] = slice
    
        arrayMap[0][0]++ // works, because it's a pointer to the array
        sliceMap[0][0]++
    
        fmt.Println(*arrayMap[0])
        fmt.Println(sliceMap[0])
    }
    
    // outputs
    [2 2 3]
    [2 2 3]
    

    This works and increments the [0] index of array to 2, as expected.

    It works because Go graciously dereferences pointers for us to its value when read and updates the value during re-assignment.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 php 将rtmp协议转hls协议,无法播放
  • ¥15 miniconda安装不了
  • ¥20 python代码编写
  • ¥20 使用MPI广播数据遇到阻塞
  • ¥15 TinyMCE如何去掉自动弹出的“链接…”工具?
  • ¥15 微信支付转账凭证,如何解决
  • ¥15 在win10下使用指纹登录时,界面上的文字最后一个字产生换行现象
  • ¥20 使用AT89C51微控制器和MAX7219驱动器来实现0到99秒的秒表计数,有开始和暂停以及复位功能,下面有仿真图,请根据仿真图来设计c语言程序
  • ¥15 51单片机 双路ad同步采样
  • ¥15 使用xdocreport 生成word