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 微信会员卡等级和折扣规则
  • ¥15 微信公众平台自制会员卡可以通过收款码收款码收款进行自动积分吗
  • ¥15 随身WiFi网络灯亮但是没有网络,如何解决?
  • ¥15 gdf格式的脑电数据如何处理matlab
  • ¥20 重新写的代码替换了之后运行hbuliderx就这样了
  • ¥100 监控抖音用户作品更新可以微信公众号提醒
  • ¥15 UE5 如何可以不渲染HDRIBackdrop背景
  • ¥70 2048小游戏毕设项目
  • ¥20 mysql架构,按照姓名分表
  • ¥15 MATLAB实现区间[a,b]上的Gauss-Legendre积分