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.

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

报告相同问题?

悬赏问题

  • ¥15 神经网络怎么把隐含层变量融合到损失函数中?
  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动