切片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的关系
发布评论