go中切片len和cap的关系

数组的长度是固定不变的,而切片的长度是可变的,它会随着切片的数据增长而增大,但是不会随着数据减少而减小。

定义切片

example1
package main

import "fmt"

func main() {

	test1 := make([]int,10)
	fmt.Printf("len is %d\n",len(test1))
	fmt.Printf("cap is %d", cap(test1))
}

结果

len is 10
cap is 10
Process exiting with code: 0

可以看出在make定义后,没有指定cap的大小的时候len和cap是相等的

example2
package main

import "fmt"

func main() {

	test1 := make([]int,10,20)
	fmt.Printf("len is %d\n",len(test1))
	fmt.Printf("cap is %d", cap(test1))
}

结果

len is 10
cap is 20
Process exiting with code: 0

定义cap后,len和cap的值就不相等了。但是cap定义的值要大于len的值,否则就会报错。

len larger than cap in make([]int)

默认情况下切片cap值小于1024的时候是成倍数增长的。比如有1变为2在变为4……但是超过1024后就变为原切片的1.25倍。

example3
package main

import "fmt"

func main() {
	
	test1 := make([]int,1024)
	test1 = append(test1,1)
	fmt.Printf("test1 len is %d\n",len(test1))
	fmt.Printf("test1 cap is %d\n", cap(test1))
	test2 := make([]int,4)
	test2 = append(test2,1)
	fmt.Printf("test2 len is %d\n",len(test2))
	fmt.Printf("test2 cap is %d", cap(test2))

}

结果

test1 len is 1025 //1024+1
test1 cap is 1280 //1024*1.25
test2 len is 5	//4+1
test2 cap is 8	//4*2
Process exiting with code: 0
  • 4
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值