slice append
tags: learning go programming
content
Note
appendmight create a new array (a new underlying array of the slice).
that’s why when callingappend, we need to assign it back to the original function
(mySlice = append(mySlice, 1))
- when appending to an underlying slice that has reached max capacity, Go creates a new backing array
- when appending to an underlying slice that has NOT reached max capacity, Go uses existing array
func main() {
a := make([]int, 3, 3)
b := make([]int, 3, 10)
c := append(a, 4)
d := append(a, 5)
fmt.Println("c is: ", c, ", addr of c is: ", &c[0])
fmt.Println("d is: ", d, ", addr of d is: ", &d[0])
e := append(b, 4)
f := append(b, 5)
fmt.Println("e is: ", e, ", addr of e is: ", &e[0])
fmt.Println("f is: ", f, ", addr of f is: ", &f[0])
}this code gives the fellowing output
c is: [0 0 0 4] , addr of c is: 0x1400012a030
d is: [0 0 0 5] , addr of d is: 0x1400012a060
// c and d has different addresses
e is: [0 0 0 5] , addr of e is: 0x1400012e000
f is: [0 0 0 5] , addr of f is: 0x1400012e000
// e and f has the same addressesup
go-slice-and-array go-slice-and-array-memory