You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Go切片不同截取方式下容量差异的原因咨询

Go切片截取后容量差异的原因解析

首先明确Go切片的核心特性:切片是底层数组的视图,其**容量(cap)**指的是从切片在底层数组中的起始索引,到底层数组末尾的元素总数。

原切片的基础信息

你定义的初始切片 s := []int{1, 2, 3, 4, 5, 6} 是直接通过字面量创建的,它对应的底层数组是长度为6的数组,切片的起始索引为0,因此初始len=6、cap=6。

对两个示例的具体分析

Example 1:s = s[:4]

这个切片操作是从起始索引0截取到索引4(左闭右开),新切片的底层数组起始索引仍然是0。根据容量的计算规则:
cap = 底层数组总长度 - 切片起始索引
也就是 6 - 0 = 6,所以新切片的容量保持6不变。

Example 2:s = s[2:]

这个切片操作是从起始索引2截取到数组末尾,新切片的底层数组起始索引变为2。代入容量计算公式:
cap = 6 - 2 = 4
因此新切片的容量变成4。

验证代码与输出

代码如下:

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]

内容的提问来源于stack exchange,提问作者Aurora Borealis

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.24 21:22:14