1. 程式人生 > >go語音基礎之append擴容特點

go語音基礎之append擴容特點

1、append擴容特點

示例:

package main //必須有個main包

import "fmt"

func main() {
	//如果超過原來的容量,通常以2倍容量擴容
	s := make([]int, 0, 1) //長度為0,容量為1
	oldCap := cap(s)
	for i := 0; i < 20; i++ {
		s = append(s, i)
		if newCap := cap(s); oldCap < newCap {
			fmt.Printf("cap: %d ===> %d\n", oldCap, newCap)

			oldCap = newCap
		}
	}

}

執行結果:  

cap: 1 ===> 2
cap: 2 ===> 4
cap: 4 ===> 8
cap: 8 ===> 16
cap: 16 ===> 32