how does array size grow when using append

tags: learning go programming

content

  • in Go, when using slice append, it automatically creates a new array, copies the array over, and increases the size of the underlying array
  • the size is increased by original size x 2
slice := make([]int, 1)
var memAddr *int
for i := range 30 {
	slice = append(slice, i)
	if memAddr == &slice[0] {
		continue
	}
	memAddr = &slice[0]
	fmt.Println(i+1, "underlying array changed!")
	fmt.Printf("addr of underlying array: %p\n", slice)
}
  • running the above code, we can see, memory address changes when i+1 is 1, 2, 4, 8, 16
  • which means, the size of underlying array pointed to by slice is 1, 2, 4, 8, 16

up

down

reference