Len Cap append Copy (len Cap append copy)

Section replication

Copy of slices, just to remind you, we used copy

 slice2 := make([]int, len(slice1), cap(slice1)) /* Copy the contents of slice1 to slice2 */ copy(slice2, slice1) // note that the back is copied to the frontCopy the code

There’s another way to slice and copy, which is faster

 slice3 :=  slice2[:]
Copy the code

Slice3 and Slice2 are the same slice. No matter which slice is changed, the other one will change.

Intercept some elements

The reason why a slice is a slice is that it can intercept some elements

The value of slice2 is [0 0 0 4 5 6], and now there is a requirement to intercept the second element

slice3 := slice2[0:1]
Copy the code

The output

len=1 cap=10 slice=[0]
Copy the code

We modify slice3 and slice2 respectively

slice3[0] = 1
slice2[0] = 2
printSlice(slice2)
printSlice(slice3)
Copy the code

Found that the output

len=6 cap=10 slice=[2 0 0 4 5 6]
len=1 cap=10 slice=[2]
Copy the code

Note that the truncated elements are still the same block of memory (slices are of reference type).

So once you’ve intercepted some elements, you have to copy them again, as follows.

slice2 = []int{0, 0, 0, 1, 2, 3}
 slice3 = make([]int, 1, 1)
 copy(slice3, slice2[0:1])
Copy the code

Tool function supplement

Sort utility function

slice2 = []int{0, 3, 0, 1, 2, 0}
 sort.Ints(slice2)
 fmt.Println(slice2)
Copy the code

The output

[0 0 0 1 2 3]
Copy the code

Sorting user-defined data set reference https://coding3min.com/785.html

This article is formatted using MDNICE