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条)

报告相同问题?

悬赏问题

  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算
  • ¥15 powerbuilder中的datawindow数据整合到新的DataWindow
  • ¥20 有人知道这种图怎么画吗?
  • ¥15 pyqt6如何引用qrc文件加载里面的的资源
  • ¥15 安卓JNI项目使用lua上的问题
  • ¥20 RL+GNN解决人员排班问题时梯度消失
  • ¥60 要数控稳压电源测试数据
  • ¥15 能帮我写下这个编程吗
  • ¥15 ikuai客户端l2tp协议链接报终止15信号和无法将p.p.p6转换为我的l2tp线路