duan19750503 2018-04-19 02:05
浏览 99
已采纳

为什么在go中切片比索引1的长度多但不超过长度

package main

import (
    "fmt"
)

func main() {
    s:= []int{1,2}
    fmt.Println(s[0:]) // this is expected
    fmt.Println(s[1:]) // this is expected
    fmt.Println(s[2:]) // this wondering why i didn't recieve slice bounds out of range error
    fmt.Println(s[3:]) // here i recieve the error
}

Can some one explain why s[2:] returns empty slice [] but s[3:] errors out. i thought s[2:] should error out too.

  • 写回答

2条回答 默认 最新

  • doucuodan0897 2018-04-19 02:45
    关注

    Based on The Go Programming Language Specifications

    For arrays or strings, the indices are in range if 0 <= low <= high <= len(a), otherwise they are out of range. For slices, the upper index bound is the slice capacity cap(a) rather than the length.

    https://golang.org/ref/spec#Slice_expressions

    s[3:] gives an error because your low index (which is 3) is greater than len(s) (which is 2) and therefore out of range

    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.

    s[2:] gives you an empty slice because your low index (which is 2) and your high index (which defaults to 2 by golang spec), which results in a slice with a length of 0 (high - low)

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

报告相同问题?

悬赏问题

  • ¥15 Vue3 大型图片数据拖动排序
  • ¥15 划分vlan后不通了
  • ¥15 GDI处理通道视频时总是带有白色锯齿
  • ¥20 用雷电模拟器安装百达屋apk一直闪退
  • ¥15 算能科技20240506咨询(拒绝大模型回答)
  • ¥15 自适应 AR 模型 参数估计Matlab程序
  • ¥100 角动量包络面如何用MATLAB绘制
  • ¥15 merge函数占用内存过大
  • ¥15 使用EMD去噪处理RML2016数据集时候的原理
  • ¥15 神经网络预测均方误差很小 但是图像上看着差别太大