go的make切片 注意事项
注意:此处make是产生长度5容量10的切片,前5个是空的,当使用append的时,前面几个还是空的
点击查看代码
package main
import(
"fmt"
)
func lenA(){
var a []string = make([]string,5,10) // 注意:此处make是产生长度5容量10的切片,前5个是空的,
print("len(a):",len(a)," cap(a):",cap(a),"\n")
fmt.Println("a", a)
fmt.Println("a0", a[0], "end a0")
fmt.Println("a1", a[1], "end a0")
fmt.Println("a2", a[2], "end a0")
fmt.Println("a3", a[3], "end a0")
fmt.Println("a4", a[4], "end a0")
//fmt.Println("a5", a[5], "end a0")
//fmt.Println("a6", a[6], "end a0")
len_a := len(a)
for i:= 0; i<100; i++{
if i < len_a{
a[i] = fmt.Sprintf("%d", i)
} else {
a = append(a, fmt.Sprintf("%d", i))
}
}
fmt.Printf("a:%v \n",a)
fmt.Println("a0>>", a[0], "end a0<<")
fmt.Println("a1>>", a[1], "end a0<<")
fmt.Println("a2>>", a[2], "end a0<<")
fmt.Println("a3>>", a[3], "end a0<<")
fmt.Println("a4>>", a[4], "end a0<<")
fmt.Println("a5>>", a[5], "end a0<<")
fmt.Println("a6>>", a[6], "end a0<<")
}
func lenB(){
var b []string = make([]string,5,10) // 注意:此处make是产生长度5容量10的切片,前5个是空的,
print("len(b):",len(b)," cap(b):",cap(b),"\n")
fmt.Println("b", b)
fmt.Println("b0", b[0], "end b0")
fmt.Println("b1", b[1], "end b0")
fmt.Println("b2", b[2], "end b0")
fmt.Println("b3", b[3], "end b0")
fmt.Println("b4", b[4], "end b0")
//fmt.Println("b5", b[5], "end b0")
//fmt.Println("b6", b[6], "end b0")
for i:= 0; i<100; i++{
b = append(b, fmt.Sprintf("%d", i))
}
fmt.Printf("b:%v \n",b)
fmt.Println("b0>>", b[0], "end b0<<")
fmt.Println("b1>>", b[1], "end b0<<")
fmt.Println("b2>>", b[2], "end b0<<")
fmt.Println("b3>>", b[3], "end b0<<")
fmt.Println("b4>>", b[4], "end b0<<")
fmt.Println("b5>>", b[5], "end b0<<")
fmt.Println("b6>>", b[6], "end b0<<")
}
func main(){
lenA()
lenB()
}
输出:
点击查看代码
a [ ]
a0 end a0
a1 end a0
a2 end a0
a3 end a0
a4 end a0
a:[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28
29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55
56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 8
2 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
a0>> 0 end a0<<
a1>> 1 end a0<<
a2>> 2 end a0<<
a3>> 3 end a0<<
a4>> 4 end a0<<
a5>> 5 end a0<<
a6>> 6 end a0<<
b [ ]
b0 end b0
b1 end b0
b2 end b0
b3 end b0
b4 end b0
b:[ 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 2
7 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80
81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99]
b0>> end b0<<
b1>> end b0<<
b2>> end b0<<
b3>> end b0<<
b4>> end b0<<
b5>> 0 end b0<<
b6>> 1 end b0<<
len(a):5 cap(a):10
len(b):5 cap(b):10
写入自己的博客中才能记得长久