douke1954 2018-08-28 10:51
浏览 20

从地图值附加切片不会影响地图

mp := map[int][]int{}
slice := make([]int, 0, 1)
fmt.Printf("slice address:%p
", slice)
mp[0] = slice
slice = append(slice, 1)
fmt.Println("after append")
fmt.Printf("slice address:%p
", slice)
fmt.Println("slice:", slice)
fmt.Println("mp[0]:", mp[0])
fmt.Printf("mp[0] address:%p
", mp[0])  

output:

slice address:0xc042008f78  
after append  
slice address:0xc042008f78  
slice: [1]  
mp[0]: []  
mp[0] address:0xc042008f78

The address of the slice does not change as its cap is large enough during append. So why the map value does not take effect?

  • 写回答

3条回答 默认 最新

  • douan5151 2018-08-28 11:01
    关注

    This is caused by the fact, that multiple slices can be backed by the same data but use different "sections" of the data. This means, that yes, an element is added to the data backing mp[0], but the length of the slice in mp is not changed. You can do that manually:

    fmt.Println(mp[0][:1])
    

    which does print [1].

    You can grow any slice to it's capacity without changing the underlying data by using slice[:cap(slice)]. slice[:n] will panic if cap(slice) < n. slice[n] on the other hand will panic when len(slice) <= n. I assume that the former is possible to allow the growing of slices without changing the underlying data (as far as that is possible). The latter, I would say, is "normal" behavior.

    This also explains why mp[0][:2] panics, as cap(mp[0]) is 1.

    For more details you might want to read this official blog post, as suggested by Flimzy.

    评论

报告相同问题?

悬赏问题

  • ¥15 基于卷积神经网络的声纹识别
  • ¥15 Python中的request,如何使用ssr节点,通过代理requests网页。本人在泰国,需要用大陆ip才能玩网页游戏,合法合规。
  • ¥100 为什么这个恒流源电路不能恒流?
  • ¥15 有偿求跨组件数据流路径图
  • ¥15 写一个方法checkPerson,入参实体类Person,出参布尔值
  • ¥15 我想咨询一下路面纹理三维点云数据处理的一些问题,上传的坐标文件里是怎么对无序点进行编号的,以及xy坐标在处理的时候是进行整体模型分片处理的吗
  • ¥15 CSAPPattacklab
  • ¥15 一直显示正在等待HID—ISP
  • ¥15 Python turtle 画图
  • ¥15 stm32开发clion时遇到的编译问题