donglingyi4679 2018-03-05 05:44
浏览 491

在golang中拥有nil slice和empty slice有什么意义?

What is the point of differentiating between a nil slice, ie. uninitialized slice, and an empty slice, ie. initialized but empty slice?

I understand the difference, but I'm wondering what the motivation is behind having the subtle difference between the two cases? For all intents and purposes, a nil slice and an empty slice behave the same when using them.

It seems as though if Go developers just had one case, for example only allowed empty slices, it would have simplified the mental model and eliminated sources of subtle bugs.

Is there a reason why those two use cases were created?

  • 写回答

1条回答 默认 最新

  • dpus81500574 2018-03-05 08:22
    关注

    A nil slice value needs no allocation. That might make a difference in cases where you want to build something in a slice, but often there will be no data to be appended, so the slice may remain nil, so no allocation will be required altogether.

    An empty slice might require an allocation, even if its capacity is zero.

    Also an empty slice means its length is 0, but its capacity may not be; so it's not true that "For all intents and purposes, a nil slice and an empty slice behave the same when using them.". You can allocate a slice with 0 length and a big capacity, optimizing for further appends to avoid allocations (and copying over):

    s := make([]int, 0)
    fmt.Println(s, len(s), cap(s))
    s = append(s, 1)
    fmt.Println(s, len(s), cap(s))
    
    s = make([]int, 0, 10)
    fmt.Println(s, len(s), cap(s))
    s = append(s, 1)
    fmt.Println(s, len(s), cap(s))
    

    Output of the above (try it on the Go Playground):

    [] 0 0
    [1] 1 2
    [] 0 10
    [1] 1 10
    

    What do we see? In the first example we created an empty slice with 0 length and 0 capacity. If we append an element to it, its length will become 1 (obviously), and its capacity increased to 2. This is because under the hood append() allocated a new array with size of 2 (thinking of future growth), copied the existing elements over (which was none in this case), and assigned the new element.

    In the second case we started with an empty slice but with a capacity of 10. This means we can append 10 elements to it without causing a new allocation and copying existing elements. This can be a big plus when slices are big and this needs to be done many times.

    评论

报告相同问题?

悬赏问题

  • ¥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时遇到的编译问题