go中切片len和cap的关系

编程入门 行业动态 更新时间:2024-10-10 12:20:15

go中<a href=https://www.elefans.com/category/jswz/34/1769942.html style=切片len和cap的关系"/>

go中切片len和cap的关系

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

定义切片

example1
package mainimport "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 mainimport "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 mainimport "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

更多推荐

go中切片len和cap的关系

本文发布于:2024-03-09 12:23:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1724953.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:切片   关系   len   cap

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!