doukaojie8573 2016-10-29 12:15
浏览 36
已采纳

Go slice的索引符号背后的想法是什么?

I can't seem to wrap my head around the notation of indices when working with Go slices.

Given a slice s.

 s := []int{1, 2, 3, 4, 5}

I now want to create a new slice s2 = [2 3].

 s2 := s[1:3] // s2 = [2 3]

Now, what is the thought process that I should go through when accessing this value? Am I reading values starting from index 1 up to and including the third element of the slice? Or am I reading values from index 1 up to and excluding index 3?

I am not starting at index 1 and going up to index 3 and neither am I starting at position 1 and going up to position 3 as both of these would result in s2 having 3 elements.

What is the idea behind this notation?

  • 写回答

1条回答 默认 最新

  • duanlijia5864 2016-10-29 12:22
    关注

    Relevant section from the spec: Slice expressions.

    For a string, array, pointer to array, or slice a, the primary expression

    a[low : high]
    

    constructs a substring or slice. The indices low and high select which elements of operand a appear in the result. The result has indices starting at 0 and length equal to high - low.

    So s2 := s[1:3] creates a new slice with length 3 - 1 = 2, so it will contain 2 elements: s[1] and s[2].

    When slicing a slice, low should be the index of the first element you want to include (inclusive), and high should be the index of the last element that will not be incuded (high is exclusive).

    So if you want the result to include the elements [2, 3], you need to provide slicing indices 1 and 3:

    s2 := s[1:3] // will be [2, 3]
    

    What might be confusing is that the elements in your slice start with 1, but the index starts with 0.

    For reasoning behind the inclusive-exclusive indices, see related question: In a Go slice, why does s[lo:hi] end at element hi-1?

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

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看