V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
jzl
V2EX  ›  Go 编程语言

GO 切片问题求教

  •  
  •   jzl · 2019-10-03 17:47:37 +08:00 · 4047 次点击
    这是一个创建于 1660 天前的主题,其中的信息可能已经有所发展或是发生改变。

    初始化切片 s := make([]int, 3) 取 s[3:] 不会报越界错误,取 s[4:]就会越界了, 求教啊

    13 条回复    2019-10-04 01:12:02 +08:00
    Leigg
        1
    Leigg  
       2019-10-03 18:25:51 +08:00 via Android
    这个还真没碰见过,是冷知识?
    c0011
        2
    c0011  
       2019-10-03 18:32:19 +08:00
    s[3:] 是扩展切片,3 代表的是个数不是下标。
    c0011
        3
    c0011  
       2019-10-03 18:39:00 +08:00
    我上边的不对。可能就是语言的规定吧,3 代表最后一个元素并且是空(nil?)
    kidlj
        4
    kidlj  
       2019-10-03 18:42:26 +08:00
    > 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.

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

    原因未知 :)
    c0011
        5
    c0011  
       2019-10-03 18:55:25 +08:00
    @kidlj 但是 fmt.Println(s[3]) 会报错
    kidlj
        6
    kidlj  
       2019-10-03 19:00:16 +08:00   ❤️ 3
    > 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

    > For convenience, any of the indices may be omitted. A missing low index defaults to zero; a missing high index defaults to the length of the sliced operand.

    因此 s[3:] == s[3:len(a)] = s[3:3] ✓
    s[4:] == s[4:len(a)] == s[4:3] x
    kidlj
        7
    kidlj  
       2019-10-03 19:00:58 +08:00   ❤️ 1
    @c0011

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

    ref: https://golang.org/ref/spec#Index_expressions
    kidlj
        8
    kidlj  
       2019-10-03 19:01:49 +08:00
    修正:len(s) 不是 len(a)
    gamexg
        9
    gamexg  
       2019-10-03 19:27:15 +08:00 via Android   ❤️ 1
    故意的吧,
    如果 s[3:]就报错,就无法取末尾的空切片了。
    Vegetable
        10
    Vegetable  
       2019-10-03 20:27:07 +08:00
    错误信息是
    panic: runtime error: slice bounds out of range [4:3]
    6 楼说的应该就是正确答案了.
    shijiu
        11
    shijiu  
       2019-10-03 22:40:12 +08:00
    缺少的最高位是切片长度,而最高位是开区间,取 s[3:3]的话返回一个 0 长切片,应该是一个规定吧,方便判断。
    就和 s[:0]返回一个 0 长切片一样?
    Carseason
        13
    Carseason  
       2019-10-04 01:12:02 +08:00
    s[3:3]
    s[4:3]
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2927 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 26ms · UTC 03:27 · PVG 11:27 · LAX 20:27 · JFK 23:27
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.