duankuaiwang2706 2017-11-12 18:00
浏览 49
已采纳

golang slice变量assign(来自教程)

https://tour.golang.org/moretypes/11

in this tutorial, s is first assigned to

s := []int{2, 3, 5, 7, 11, 13}

then after that a series of actions are done to s

s = s[:0]
printSlice(s)  // len=0 cap=6 []
s = s[:4]
printSlice(s) // len=4 cap=6 [2 3 5 7]

I code in python normally, so this confuses me a bit. When assigning s=s[:0], shouldn't s be changed to the slice of original s, meaning the s is no longer an array but a slice? How can this slice again be assigned to a different length that actually has content in it?

  • 写回答

1条回答 默认 最新

  • dongshenchi5364 2017-11-12 18:07
    关注

    Slices in go are a fancy structure that sits on top of an array. In your example:

    s := []int{2, 3, 5, 7, 11, 13}
    

    Creates an array with the contents: 2, 3, 5, 7, 11, 13 and the slice s points to that array and it's as long as the array itself.

    When slicing s = s[:0] this creates a new slice with length 0 on the same array. Although the new slice is empty, because it shares the same array when you make the slice bigger with s = s[:4] it allows you to see the first 4 values of the array.

    Slices are like windows into an underlying array, and modifying the slice don't modify the array. So the first slice lets you see all of the elements in the array, the second one doesn't show you any of the elements and the third one let's you see only the first 4 elements.

    Here I use [] to represent what the slice a contents are in each part of your example:

    [2 3 5 7 11 13]
    []2 3 5 7 11 13
    [2 3 5 7] 11 13
    

    But the array always remains the same.

    As a note, because slicing doesn't create a new array, even if you save each of those slices in a different variable, the underlying array is the same, so if you modify one of the elements in one slice, you would see that same change in all of the slices that share the same array.

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

报告相同问题?

手机看
程序员都在用的中文IT技术交流社区

程序员都在用的中文IT技术交流社区

专业的中文 IT 技术社区,与千万技术人共成长

专业的中文 IT 技术社区,与千万技术人共成长

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

关注【CSDN】视频号,行业资讯、技术分享精彩不断,直播好礼送不停!

客服 返回
顶部