func TestSlice(t *testing.T) { //方法1:直接创建一个保存有10个整数的slice intSlice := make([]int, 10, 15) //{1, 2, 3, 4, 5, 6, 7, 8, 9, 10} for idx := 0; idx < len(intSlice); idx++ { intSlice[idx] = idx + 1 } GOUNIT_ASSERT(t, len(intSlice) == 10, "make创建的slice长度") GOUNIT_ASSERT(t, cap(intSlice) == 15, "make创建的slice容量") //从尾端向数组切片中追加元素 newIntSlice := append(intSlice, 11, 12, 13) GOUNIT_ASSERT(t, len(intSlice) == 10, "append后原来的Slice不变") GOUNIT_ASSERT(t, len(newIntSlice) == 13, "append后新的Slice") GOUNIT_ASSERT(t, cap(newIntSlice) == 15, "cap(newIntSlice) == 15") GOUNIT_ASSERT(t, &newIntSlice != &intSlice, "append返回新的切片") GOUNIT_ASSERT(t, &newIntSlice[0] == &intSlice[0], "底层的数组是同一个") newIntSlice[0] = 99 GOUNIT_ASSERT(t, newIntSlice[0] == intSlice[0], "未进行内存扩充的情况下新旧Slice指向同一个底层数组") newAddressIntSlice := append(intSlice, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20) GOUNIT_ASSERT(t, cap(newAddressIntSlice) == 30, "扩充后的长度,目前实现采用容量翻倍的方式") newAddressIntSlice[0] = 199 GOUNIT_ASSERT(t, &newAddressIntSlice[0] != &intSlice[0], "进行了内存扩充,底层数组不再一样") GOUNIT_ASSERT(t, newAddressIntSlice[0] != intSlice[0], "进行了内存扩充,底层数组不再一样") //方法2:先创建一个array,然后基于该array创建slice intArray := [10]int{0, 1, 2, 3, 4, 5, 6, 7, 8, 9} intSliceFromArray := intArray[0:5] //[:]--基于全部元素, [5:]--从第5个元素开始的所有元素 GOUNIT_ASSERT(t, len(intSliceFromArray) == 5, "array[n:m]创建的slice长度") GOUNIT_ASSERT(t, cap(intSliceFromArray) == 10, "array[n:m]创建的slice容量") GOUNIT_ASSERT(t, cap(intArray) == 10, "数组的容量") //下面代码会在运行时抛出"index out of range"的异常(panic) -- 因为该slice长度是5(即0~4) //intSliceFromArray[5] = 10 //在slice后追加slice,注意最后的三个点 S3 := append(newIntSlice, intSliceFromArray...) GOUNIT_ASSERT(t, len(S3) == 18 && cap(S3) == 30, "在slice后追加slice") //copy函数,如两个切片不一样大,会按照较小的切片的元素个数进行复制 var newS = make([]int, 3) nCopy := copy(newS, intSlice[0:5]) GOUNIT_ASSERT(t, nCopy == 3, "只复制3个元素") } |