This is a creation in Article, where the information may have evolved or changed.
In the Golang language, the data type is not many, but enough, the development project process, slice belongs to one of the most commonly used data structure, the understanding of its principle is not clear, it is easy to leave the bug, the author inquires a lot of blog material, to slice append principle to carry on a summary, If you do not know what to write, please forgive and correct it.
package mainimport "fmt"func main(){ s := []int{5} s = append(s,7) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0]) s = append(s,9) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0]) x := append(s, 11) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(x) =", &x[0]) y := append(s, 12) fmt.Println("cap(s) =", cap(s), "ptr(s) =", &s[0], "ptr(y) =", &y[0])}
Output:
cap(s) = 2 ptr(s) = 0x10328008cap(s) = 4 ptr(s) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(x) = 0x103280f0cap(s) = 4 ptr(s) = 0x103280f0 ptr(y) = 0x103280f0
Actual process:
Text Description:
- When creating S, cap (s) = = 1, in-memory data [5]
- Append (S, 7), press slice expansion mechanism, cap (s) doubled = = 2, in-memory data [5,7]
- Append (S, 9), press slice expansion mechanism, cap (s) Doubles = = 4, in-memory data [5,7,9], but actual memory block capacity 4
- x: = Append (S, 11), sufficient capacity does not require expansion, in-memory data [5,7,9,11]
- Y: = Append (S, 12), sufficient capacity does not require expansion, in-memory data [5,7,9,12]
The Append in 5 is the addition of element 12 on the basis of S, which is actually = = = From the end of the S-slice to write = =, so it covers 11