测试

go语言数组内存是怎么扩容的

话不多说,上测试代码和结果 package main import ( "fmt" ) func main() { var orderIds []int fmt.Println(len(orderIds), cap(orderIds)) fmt.Println("已使用", "\t\t", "容量", "\t\t", "增量") var lastCap = cap(orderIds) for i := 0; i < 100000; i++ { orderIds = append(orderIds, 1) if cap(orderIds) != lastCap{ fmt.Println(len(orderIds), "\t\t", cap(orderIds), "\t\t", cap(orderIds)-lastCap) lastCap = cap(orderIds) } } } 输出 0 0 已使用 容量 增量 1 2 2 3 4 2 5 8 4 9 16 8 ...

golang数组用法

package main import ( "fmt" ) var ( duration int = 2 ) func main() { fmt.Println("test case 1:") strs := make([]string, 10) strs = append(strs, "1") strs = append(strs, "2") strs = append(strs, "3") for _, val := range strs{ fmt.Println(val) } fmt.Println("test case 2:") var strs2 []string strs2 = append(strs2, "1") strs2 = append(strs2, "2") strs2 = append(strs2, "3") for _, val2 := range strs2{ fmt.Println(val2) } } 输出 test case 1: 1 2 3 test case 2: 1 2 3