This is a creation in Article, where the information may have evolved or changed.
- About Golang's slice I think is one of the features of go, it fully improved the array of several limited places, this article simple analysis of slice use process you will encounter several problems:
Let's look at the following example:
sliceA:=[]int{1,2,3}sliceB:=sliceA[0:2]sliceA[0]=4fmt.Println(sliceB)//此处输出什么?
The above code shows that slice's assignment operation is a reference type (address copy) that changes itself after the original slice is affected. Then if you want to not be affected, you can choose the copy operation:
sliceA:=[]int{1,2,3}sliceB:=make([]int,len(sliceA))copy(sliceA,sliceB)
Note the copy operation requires that the address space be created first for the operand.
Let's look at the following questions:
sliceA:=[]int{1,2,3}sliceB:=append(sliceA,4,5)sliceC:=sliceB[0:3]fmt.Println(len(sliceA),len(sliceB),len(sliceC))//输出什么?fmt.Println(cap(sliceA),cap(sliceB),cap(sliceC))//输出什么?
Correct result:
3 5 33 6 6
Analysis above you can know, append operation slice the underlying array capacity will multiply, Len is slice length, that is, the actual value of the length, cap is the capacity of the request. The concept of capacity in go needs to be thought about. The
SLICEC is assigned a value equal to SLICEB, but with a different length.