duankuaiwang2706 2017-11-13 02: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-13 02: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.

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

报告相同问题?

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来