Slice默认混淆上下限

问题描述 投票:-2回答:1
package main
import "fmt"
func main() {
    s := []int{2, 3, 5, 7, 11, 13}

    s=s[0:4]
    fmt.Println(s)  // 1st

    s = s[1:4]
    fmt.Println(s) // 2nd

    s = s[:2]
    fmt.Println(s) //3rd

    s = s[1:]
    fmt.Println(s) // 4th

    s= s[:]
    fmt.Println(s)  // 5th

    s=s[0:4]
    fmt.Println(s)  // 6th 
}

我得到的输出是这个

[2 3 5 7]
[3 5 7]
[3 5]
[5]
[5]
[5 7 11 13]

为什么在第三名只有3 5为什么不是2 3

假设我要通过这种逻辑每次切片数减少时,则:为什么最后一行有5 7 11 13。

如果假设上述逻辑错误,那么:为什么最后一行输出[5 7 11 13]为什么不以2开头

Here is the link from where I am going thru

go slice
1个回答
4
投票

切片指的是基础数组。重新切片切片不会影响基础数组。

slice表达式中的偏移量(即[0:4]中的0)是指slice的开头,而不是array的开头。因此,切出数组后,您将无法“返回”到数组的早期值。为此,您必须保持较早的slice值。

[这是可通过切片(用花括号表示)“看到”基础数组的一部分(由方括号表示)的过程:

initial:  [{2,  3,  5 , 7,  11, 13}]
s=s[0:4]: [{2,  3,  5 , 7}, 11, 13 ]
s=s[1:4]: [ 2, {3,  5 , 7}, 11, 13 ]
s=s[:2]:  [ 2, {3,  5}, 7,  11, 13 ]
s=s[1:]:  [ 2,  3, {5}, 7,  11, 13 ]
s=s[:]:   [ 2,  3, {5}, 7,  11, 13 ] // no-op
s=s[0:4]: [ 2,  3, {5 , 7,  11, 13}]

注意数组如何保持不变,并且左花括号仅向右移动(如果有的话。)>

有关更多详细信息,请参见"Go Slices: usage and internals"

© www.soinside.com 2019 - 2024. All rights reserved.