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

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
    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?

    点赞 评论

相关推荐