Go Slice's Append Trap
append in Go is destructive against how it looks on the code.
append()
in Go is destructive against how it looks on the code.
If the capacity ofs
is not large enough to fit the additional values,append
allocates a new, sufficiently large underlying array that fits both the existing slice elements and the additional values. Otherwise,append
re-uses the underlying array.
package main
import "fmt"
func main() {
test := []int{1, 2, 3, 4, 5, 6}//cap(6)
fmt.Printf("address of test %p\n", test)
test = append(test, 7)//cap(12)
// fmt.Printf("address of test %p\n", test)
test2 := append(test, []int{7,8,9}...)//len() cap(12)
fmt.Println(test)
fmt.Println(test2)
test2[0] = -1
fmt.Println(test)
fmt.Println(test2)
fmt.Printf("length of test = %v, length of test2 = %v\n", len(test), len(test2))
fmt.Printf("capacity of test = %v, capacity of test2 = %v\n", cap(test), cap(test2))
test = append(test, 10)//cap(12)
fmt.Println(test)
fmt.Println(test2)
fmt.Printf("address of test %p\n", test)
fmt.Printf("address of test2 %p\n", test2)
// fmt.Printf("address of test %p add of test2 %p \n", &test, &test2)
}