This is a creation in Article, where the information may have evolved or changed.
See Code Comment:
PackageMainImport( "FMT""Sync")funcMain() {sourcearray: = [...]string{"a", "B", "C", "D", "E", "F", "G"} fmt.Println(sourcearray) Slice_1: = sourcearray[:4] slice_2: = sourcearray[2:] Slice_3: = sourcearray[1:] Slice_4: = slice_3[1:] Slice_5: = slice_4[1:] slice_1[3] = "I" FMT.Println(Sourcearray) fmt.Println(Slice_1) fmt.Println(slice_2) fmt.Println(Slice_3) fmt.Println(Slice_4) fmt.Println(SLICE_5) WG: = &sync. waitgroup{} WG.ADD(5) /*slice, map, channel, function, method are reference types in the go language; a slice slice) is a reference to a hidden array, and a slice of that slice also references the same array. * / go func(p []string) { deferWG. Done() p[3] = "W"//p[3]-sourcearray[3] } (Slice_1)//When the function calls the parameter, because slice is a reference type, both Slice_1 and P refer to the same array sourcearray go func(p []string) { deferWG. Done() p[1] = "Z"//p[1]-sourcearray[3] } (slice_2)go func(p []string) { deferWG. Done() p[2] = "x"//p[2]-sourcearray[3] } (Slice_3)go func(p []string) { deferWG. Done() p[1] = "Q"//p[1]-sourcearray[3]//even slice slices, still point to the same array sourcearray } (Slice_4)go func(p []string) { deferWG. Done() p[0] = "T"//p[0]-sourcearray[3]//even slices of sliced slices, etc., still point to the same array sourcearray } (SLICE_5) WG.Wait() / * from the above analysis, in multi-threaded programming, co-programming, for shared variables, the read and write of resources must be serialized, such as lock, or through the channel to achieve exclusive access. from the test code above, we learned that the read and write of slices (slice) is ultimately read and write to the hidden array of slices, and if the array index range of the read-write or the element is coincident, then multiple co-processes read-write shared elements, in the case of concurrency, is bound to create competition, destroy the shared element data, so to protect, either lock, or use the channel to queue access to the serialization. Therefore, the use of slice must pay special attention to 3 points: (1) The slice is a reference type (2) a slice is a reference to a hidden array (3) slicing and slicing, etc., still pointing to the same hidden array Note: These conclusions are obtained without exceeding the tile capacity (the length of the hidden array), because the go language built-in function append allocates new larger slices and corresponding hidden arrays when the tile capacity is insufficient; but this does not affect the above conclusion, new slices, the old slices still each point to their own hidden array. */ FMT.Println("------") fmt.Println(Slice_1) fmt.Println(slice_2) fmt.Println(Slice_3) fmt.Println(Slice_4) fmt.Println(slice_5)}
Note: This article is only my personal notes, if there are errors and omissions, please correct me, study together, my e-mail: htyu_0203_39@sina.com