Slices themselves are not dynamic arrays or array pointers. Its internal data structure refers to the underlying array through a pointer, and sets related attributes to limit data reading and writing operations to a specified area. Slice itself is a read-only object, and its working mechanism is similar to an encapsulation of array pointers.
three elements of slicing:
pointer: pointing address
length: len
capacity: cap
slicing initialization, len=cap
slicing is a reference type (new address, pointing to the value at the original address), and its biggest feature is that if the value on the referenced address changes, the slicing will also change
.
Therefore, if the array is changed in the function, it will not change after it is returned
1. Slices vs arrays
2. Slices are passed by reference, so they do not need to use extra memory and are more efficient than using arrays.
3. empty slice vs nil slice
4. slice expansion:
4.1 expansion strategy
4.2 does the expansion generate a brand-new memory address or append it after the original address?
4.2.1 slice creation method 1: According to the expansion situation, whether to expand
Slice: = [] int {1, 2, 3, 4}
New Slice: = append (Slice, 5)
Go will open a memory area first by default, and copy the original value. This situation does not affect the original array at all.
4.2.2 slice literal to create a new address
Because the original array still has capacity to expand, it will be operated directly on the original array after the append () operation, so in this case, the expanded array still points to the original array.
array: = [4] int {1, 2, 3, 4}
Slice: = array [: 2]
New Slice: = Append (Slice, 5)
Detailed reference link
Print result:
Not all the time. Because slicing the underlying array make allocate memory on the heap, and the consumption of copying small arrays on the stack is also less than that of making
Learning the link
Use of sync/atomic
unsafe.Pointer
Summary of Go: