Slice memory analysis and expansion

Slice slice:

  1. Each slice refers to an underlying array
  2. The slice itself does not store any data, but is the underlying array storage, so modifying the slice means modifying the data in the array
  3. When adding data to a slice, add data directly if it does not exceed the capacity. Automatic expansion (double growth)
  4. When a slice is expanded, it points back to a new underlying array
Package main import "FMT" func main() {s1:=[]int{1,2,3} FMT.Println(s1) FMT.Printf(" length :%d, capacity :%d \n",len(s1),cap(s1)) FMT. Printf (" % p \ n ", s1) s1 = append (s1, 4, 5) FMT. Println (s1) FMT. Printf (" length is: % d, capacity of % d \ n ", len (s1), cap (s1)) FMT. Printf (" % p \ n ", s1) s1 = append (s1, June) FMT. Println (s1) FMT. Printf (" length is: % d, capacity of % d \ n ", len (s1), cap (s1)) FMT. Printf (" % p \ n ", s1) s1 = append (s1, 9, 10) FMT. Println (s1) FMT. Printf (" length is: % d, capacity of % d \ n ", len (s1), cap (s1)) FMT. Printf (" % p \ n ", s1) s1 = append (s1, 11,12,13,14,15) FMT. Println (s1) FMT. Printf (" length is: % d, capacity of % d \ n ", len (s1), cap (s1)) fmt.Printf("%p\n",s1) }Copy the code

Creates a slice on an existing array

Slice :=arr[start:end] Data in a slice: [start,end] arr[:end] From start to end ARr [start:] From start to end Create a slice on an existing array. The underlying array of the slice is the current array. Length is the amount of data cut from start to end. But the capacity goes from start to the end of the arrayCopy the code
Package main import "FMT" func main() {a:=[10]int{1,2,3,4,5,6,7,8,9,10} FMT.Println("1. From the existing array directly create slice ") s1: = [5] s2: a = a s3: [when] = [5:] s4: a = a [:] FMT Println (" a ", a) FMT. Println (" s1 ", s1) FMT. Println (" s2 ", s2) fmt.Println("s3",s3) fmt.Println("s4",s4) fmt.Printf("%p\n",&a) fmt.Printf("%p\n",s1) fmt.Println("2. Length and capacity ") FMT. Printf (" s1 len: % d, cap: % d \ n ", len (s1), cap (s1) FMT) Printf (" s2 len: % d, cap: % d \ n ", len (s2), cap (s2)) FMT) Printf (" s3  len:%d,cap:%d\n",len(s3),cap(s3)) fmt.Printf("s4 len:%d,cap:%d\n",len(s4),cap(s4)) fmt.Println("3. ") a[4]=100 fmt.println ("a",a) fmt.println ("s1",s1) fmt.println ("s2",s2) fmt.println ("s3",s3) fmt.Println("s4",s4) fmt.Println("4. ") s1=append(s1,1,1) FMT.Println("s1", a) FMT.Println("s1",s1) FMT.Println("s2",s2) FMT.Println("s2",s2) FMT.Println("s3",s3) fmt.Println("s4",s4) fmt.Println("5. ") s1=append(s1,2,2,2,2,2, 2) FMT.Println("s1", a) FMT.Println("s1",s1) FMT.Println("s2",s2) FMT.Println("s3",s3) fmt.Println("s4",s4) fmt.Println(len(s1),cap(s1)) fmt.Printf("%p\n",s1) fmt.Printf("%p",&a) }Copy the code