dongyejun1983 2016-08-15 18:23
浏览 78
已采纳

去切片-[:n]和[n:]之间的区别

Go Slice question, please check below and comment if I am missing something.

   import "fmt"
   func main() {
       s := []int{2, 3, 5, 7, 11, 13}
       s = s[1:]
       fmt.Println(s)
       s = s[2:]
       fmt.Println(s)
       s = s[5:]
       fmt.Println(s)
  }

Output:

[3 5 7 11 13] [7 11 13] panic: runtime error: slice bounds out of range

The above makes sense.

func main() {
       s := []int{2, 3, 5, 7, 11, 13}
       s = s[:1]
       fmt.Println(s)
       s = s[:2]
       fmt.Println(s)
       s = s[:5]
       fmt.Println(s)
   }

Output:

[2] [2 3] [2 3 5 7 11]

Should this also get array out of bounds panic from s=s[:2]?

  • 写回答

2条回答 默认 最新

  • doubi1713 2016-08-15 18:39
    关注

    Subslicing in Go allows you to slice beyond the end of the slice, as long as it's still within range of the underlaying array's capacity. You cannot slice before the start of that slice, but you can slice after it so long as you don't go past that last allocated index.

    As an example, s[3:] then s[:3] works, but s[4:] then s[:4] will panic, as you're requesting indexes 4 through 7 of the underlying array, which only has allocated indexes 0-5.

    It's a bit of an oddity, but it does allow you to max out any slice simply by doing slice = slice[:cap(slice)].

    https://play.golang.org/p/Gq5xoXc3Vd

    The language specification annotes this, btw. I've paraphrased it below for the simple slice notation you're using (there's an alternative that also specifies the maximum index for the new slice).

    For a string, array, pointer to array, or slice a, the primary expression a[low : high] constructs a substring or slice. The indices are in range if 0 <= low <= high <= cap(a), otherwise they are out of range.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 拟通过pc下指令到安卓系统,如果追求响应速度,尽可能无延迟,是不是用安卓模拟器会优于实体的安卓手机?如果是,可以快多少毫秒?
  • ¥20 神经网络Sequential name=sequential, built=False
  • ¥16 Qphython 用xlrd读取excel报错
  • ¥15 单片机学习顺序问题!!
  • ¥15 ikuai客户端多拨vpn,重启总是有个别重拨不上
  • ¥20 关于#anlogic#sdram#的问题,如何解决?(关键词-performance)
  • ¥15 相敏解调 matlab
  • ¥15 求lingo代码和思路
  • ¥15 公交车和无人机协同运输
  • ¥15 stm32代码移植没反应