slice golang learning

1.slice nature

pointer + len + cap

pointer points to a period of real array

len from the starting address pointing to the beginning of the number of elements
cap capacity of this array (when the append, automatically expansion capacity is insufficient)

 

2.slice interesting experiment

 1 func main() {
 2     var array []int32 = []int32{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
 3     var slice = array[0:10]
 4     fmt.Println("原始array[0]:", array[0])
 5     slice[0] = 2
 6     fmt.Println("新的array[0]:", array[0])
 7     slice = append(slice, 11)
 8     //fmt.Println("新的array[10]:", array[10])
 9     slice[0] = 3
10     fmt.Println("新的array[0]:", array[0])
11     fmt.Println("新的slice[0]:", slice[0])
12 }

Output:

 

 The first two outputs, modify the value of the slice, the original is also modified, indicating the nature of a slice pointer

After two outputs, modify the value of the slice, the original have not been modified since the cap is not enough slice, automatically expansion (expansion experiments attempting to discover the cap is generally twice that of the original, and is a multiple of 4)

  After the expansion slice is a new address, it is not related to the original one.

Guess you like

Origin www.cnblogs.com/ayaoyao/p/11442529.html