golang slice
golang 在for range一个slice时,会读出其cap长度。在for的过程中,即使动态append该slice,最终for也会在第一次读取的cap长度处停止。
package main import ( "fmt" ) func main() { s := make([]string, 3) s[0]="a" s[1]="b" s[2]="c" for _,i := range s { s = append(s, s[0]) fmt.Println("len", len(s)) fmt.Println("cap", cap(s)) fmt.Println("i", i) fmt.Println("s", s) } s = append(s, "e") fmt.Println(">>>len", len(s)) fmt.Println(">>>cap", cap(s)) fmt.Println(">>>s", s) }
输出为:
len 4
cap 6
i a
s [a b c a]
len 5
cap 6
i b
s [a b c a a]
len 6
cap 6
i c
s [a b c a a a]
>>>len 7
>>>cap 12
>>>s [a b c a a a e]