This is a creation in Article, where the information may have evolved or changed.
Slice slice is the reference type Len () function Gets the number of elements of the CAP () gets the capacity of the array
1. Means of declaration
(1) var a []int differs from array is that he does not declare length
(2) S2: = Make ([]int, 3, 10)//type of element, number of elements, capacity of element
Fmt. Println (len (S2), Cap (S2)) The number and capacity of output elements
2. Convert arrays into slices
2 A: = [ten]int{}3FMT. Println (a)4 S1: = a[:ten] //5 FMT. Println (S1)
3.slice Test
1A: = []byte{'a','b','C','D','e','F','h'}2SA: = a[2:5]3Fmt. Println (string(SA))4SD1: = a[3:5]5Fmt. Println (string(SD1))//look at the effect
What we see is that slice_a point to Array_ori is actually pointing from C to K we use FMT. Println (Cap (slice_a)) The result is definitely not 3.
Try it on your own.
A: = []byte{'a','b','C','D','e','F','h'} SA:= a[2:5]fmt. Println (string(SA)) s:= sa[1:3] FMT. Println (string(s)) S2:= sa[3:5] FMT. Println (string(S2))
Usage of 4.Apppend
When using append, we append the element to the end of the slice, and if we append it to the slice capacity we will find that
Memory address is not changed, if we append more than capacity, the memory address will change
1A: = Make ([]int,3,6)2Fmt. Printf ("%p", a)3A = append (A,1,2,3)4Fmt. Printf ("%v%p\n", A, a)5A = append (A,1,2,3)6Fmt. Printf ("%v%p\n", A, a)
Run as
Slice is a pointer to the underlying array, and if more than one slice points to the same time, one of them changes and the other changes. Try the bottom one.
1 A: = []int{12345}2 S1: = a[2 :5]3 s2: = a[1:3]4FMT. Println (S1, S2)5 s1[096 fmt. Println (S1, S2)
When an element appended to append in slice exceeds the pointed capacity, it points back to a new underlying array,
So a change in the underlying array does not drive other changes,
Try the code below.
1 2A: = []int{1,2,3,4,5}3S1: = a[2:5]4S2: = a[1:3]5 FMT. Println (S1, S2)6S2 = append (s2,1,2,2,3,3,4,5)7s1[0] =98Fmt. Println (S1, S2)
5.copy
This is a copy of the function, the code below is copied from S2 to S1 and we will see the result is [7 8 9 4 5]
If it is copy (S2,S1) we see the result [1 2 3]
S1: = []int{12345}s2:= []int{7 89}copy (S1, S2) fmt. Println (S1)
Reprinted from the Micro-degree network http://www.widuu.com/archives/08/771.html