douchen7555 2018-09-10 03:29
浏览 40
已采纳

在这种情况下,为什么不报告“切片范围超出范围”? [重复]

This question already has an answer here:

Here's the code to reproduce:

package main

import "fmt"

func main() {
    var v []int
    v = append(v,1)
    v = append(v,v[1:]...)
    fmt.Println("hi", v)

}

v[1] will report index out of range, but v[1:]... won't, why?

</div>
  • 写回答

3条回答 默认 最新

  • doushansu9012 2018-09-10 03:37
    关注

    That's how spec defines slice expressions

    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

    And that's how index expressions for slices are defined

    the index x is in range if 0 <= x < len(a), otherwise it is out of range

    if x is out of range at run time, a run-time panic occurs

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

    For your example:

    v[1] panics because it's our of range as per the definition above (because 1 does not qualify the 0 <= x < len(a) reqirement)

    v[1:] runs fine because it's identical to v[1:len(v)] and fits the if 0 <= low <= high <= cap(a) requirement.

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

报告相同问题?

悬赏问题

  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办
  • ¥15 kylin启动报错log4j类冲突
  • ¥15 超声波模块测距控制点灯,灯的闪烁很不稳定,经过调试发现测的距离偏大