package main import ( "fmt" ) func main() { a := []string{"A", "B", "C", "D", "E"} a = nil fmt.Println(a, len(a), cap(a)) }
result: [] 0 0
说明: a 是 一个nil 的slice
package main import ( "fmt" ) func main() { a := []string{"A", "B", "C", "D", "E"} a = a[:0] //空的slice fmt.Println(a, len(a), cap(a)) }
result [] 0 5
说明 a是长度是0的emtpy slice
slice的底层表示形式
[pointer] [length] [capacity]
nil slice: [nil][0][0] empty slice: [addr][0][0] // pointer是底层数组的地址
package main import ( "fmt" ) func main() { var nilSlice []string emptySlice0 := make([]int, 0) var emptySlice1 = []string{} fmt.Printf("\nNil:%v Len:%d Capacity:%d", nilSlice == nil, len(nilSlice), cap(nilSlice)) fmt.Printf("\nnil:%v Len:%d Capacity:%d", emptySlice0 == nil, len(emptySlice0), cap(emptySlice0)) fmt.Printf("\nnil:%v Len:%d Capacity:%d", emptySlice1 == nil, len(emptySlice1), cap(emptySlice1)) }
package main import "fmt" func main() { s1 := make([]int, 5) fmt.Printf("The length of s1: %d\n", len(s1)) fmt.Printf("The capacity of s1: %d\n", cap(s1)) fmt.Printf("The value of s1: %d\n", s1) s2 := make([]int, 5, 8) fmt.Printf("The length of s2: %d\n", len(s2)) fmt.Printf("The capacity of s2: %d\n", cap(s2)) fmt.Printf("The value of s2: %d\n", s2) }
make 初始化slice