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?

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

报告相同问题?

悬赏问题

  • ¥50 如何增强飞上天的树莓派的热点信号强度,以使得笔记本可以在地面实现远程桌面连接
  • ¥15 MCNP里如何定义多个源?
  • ¥20 双层网络上信息-疾病传播
  • ¥50 paddlepaddle pinn
  • ¥20 idea运行测试代码报错问题
  • ¥15 网络监控:网络故障告警通知
  • ¥15 django项目运行报编码错误
  • ¥15 STM32驱动继电器
  • ¥15 Windows server update services
  • ¥15 关于#c语言#的问题:我现在在做一个墨水屏设计,2.9英寸的小屏怎么换4.2英寸大屏