首页 > 代码库 > golang slice

golang slice

golang 在for range一个slice时,会读出其cap长度。在for的过程中,即使动态append该slice,最终for也会在第一次读取的cap长度处停止。

package mainimport (    "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 4cap 6i as [a b c a]len 5cap 6i bs [a b c a a]len 6cap 6i cs [a b c a a a]
>>>len 7>>>cap 12>>>s [a b c a a a e]
 

golang slice