The Go Programming Language
› http://golang.org/
› Go Playground
Go Projects
› Revel Web Framework
jzl

GO 切片问题求教

  •  
  •   jzl · Oct 3, 2019 · 5078 views
    This topic created in 2603 days ago, the information mentioned may be changed or developed.

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

    13 replies  •  2019-10-04 01:12:02 +08:00
    Leigg
    Leigg
    Oct 3, 2019 via Android
    1
    这个还真没碰见过,是冷知识?
    c0011
    c0011
    Oct 3, 2019
    2
    s[3:] 是扩展切片,3 代表的是个数不是下标。
    c0011
    c0011
    Oct 3, 2019
    3
    我上边的不对。可能就是语言的规定吧,3 代表最后一个元素并且是空(nil?)
    kidlj
    kidlj
    Oct 3, 2019
    4
    > 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
    c0011
    Oct 3, 2019
    5
    @kidlj 但是 fmt.Println(s[3]) 会报错
    kidlj
    kidlj
    Oct 3, 2019❤️3
    6
    > 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
    kidlj
    Oct 3, 2019❤️1
    7
    @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
    kidlj
    Oct 3, 2019
    8
    修正:len(s) 不是 len(a)
    gamexg
    gamexg
    Oct 3, 2019 via Android❤️1
    9
    故意的吧,
    如果 s[3:]就报错,就无法取末尾的空切片了。
    Vegetable
    Vegetable
    Oct 3, 2019
    10
    错误信息是
    panic: runtime error: slice bounds out of range [4:3]
    6 楼说的应该就是正确答案了.
    shijiu
    shijiu
    Oct 3, 2019
    11
    缺少的最高位是切片长度,而最高位是开区间,取 s[3:3]的话返回一个 0 长切片,应该是一个规定吧,方便判断。
    就和 s[:0]返回一个 0 长切片一样?
    Carseason
    Carseason
    Oct 4, 2019
    13
    s[3:3]
    s[4:3]
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Privacy   ·   Solana   ·   4159 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 58ms · UTC 09:17 · PVG 17:17 · LAX 01:17 · JFK 04:17
    ♥ Do have faith in what you're doing.