golang的cap与len小结

小结

cap主要是为了让slice提供可变长度

概念

cap 数据类型的容量

len 数据类型的实际长度

// 数据类型为 切片,长度为5,容量为10 
a := make([]int,5,10) 
fmt.Println(a,cap(a),len(a)) // out put : [0 0 0 0 0] 10 5 

// 切片追加元素,当超过原来的的容量的时候,会翻倍扩容,但不是一定翻倍,如果容量太大不会再翻倍 
for i:=0;i<10;i++  {
    a = append(a, i) 
}
// 再对值进行修改 
for i:=0;i<10;i++  {
    a[i] = i
}
fmt.Println(a,cap(a),len(a)) // [0 1 2 3 4 5 6 7 8 9 5 6 7 8 9] 20 15
欢迎留言评论~
原文地址:https://www.cnblogs.com/issac-fan/p/12826883.html