Golang 在以不同方式切片时表现出不同的能力

问题描述 投票:0回答:0

我试图理解 Go 中的切片,并且遇到了以下代码(Go playground):

package main

import "fmt"

func main() {
    s := []int{1, 2, 3, 4, 5, 6}
    example1(s)
    fmt.Printf("\n")
    example2(s)
}

func example1(s []int) {
    fmt.Printf("Example 1: \n")
    printSlice(s)

    s = s[:4]
    printSlice(s)
}

func example2(s []int) {
    fmt.Printf("Example 2: \n")
    printSlice(s)

    s = s[2:]
    printSlice(s)
}

func printSlice(s []int) {
    fmt.Printf("len=%d cap=%d %v\n", len(s), cap(s), s)
}

输出为:

Example 1: 
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=6 [1 2 3 4]

Example 2: 
len=6 cap=6 [1 2 3 4 5 6]
len=4 cap=4 [3 4 5 6]

虽然切片的长度看起来不错,但我不明白的是为什么切片后的容量在第一个示例中为

6
,而在第二个示例中为
4

arrays go slice
© www.soinside.com 2019 - 2024. All rights reserved.