声明一个数组
var arr = [10]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var arr1 = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", arr, len(arr), cap(arr), arr)
fmt.Printf("比较,类型: %T 结果: %v \n", arr == [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}, arr == [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10})
fmt.Printf("比较,类型: %T 结果: %v \n", arr == arr1, arr == arr1)
基于数组创建一个切片
var arr = [...]int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var slice = arr[:]
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", arr, len(arr), cap(arr), arr)
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", slice, len(slice), cap(slice), slice)
切片截取
var slice1 = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
var slice2 = slice1[3:6]
slice3 := slice1[3:6:9]
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", slice1, len(slice1), cap(slice1), slice1)
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", slice2, len(slice2), cap(slice2), slice2)
fmt.Printf("类型: %T 长度: %v 容量: %v 值为: %v \n", slice3, len(slice3), cap(slice3), slice3)
slice4 := slice2[:cap(slice2)]
slice5 := slice3[:cap(slice3)]
fmt.Printf("slice4 ==> %v \n", slice4)
fmt.Printf("slice5 ==> %v \n", slice5)
切片拷贝
var slice1 = []int{1, 2, 3, 4, 5, 6, 7, 8, 9, 10}
slice2 := slice1[4:7]
fmt.Printf("slice1 ==> %v \n", slice1)
fmt.Printf("slice2 ==> %v \n", slice2)
slice2[1] = 123
fmt.Printf("slice1 ==> %v \n", slice1)
fmt.Printf("slice2 ==> %v \n", slice2)
var slice3 []int
copy(slice3, slice2)
fmt.Printf("slice1 ==> %v \n", slice1)
fmt.Printf("slice2 ==> %v \n", slice2)
fmt.Printf("slice3 ==> %v \n", slice3)
slice4 := make([]int, len(slice2))
copy(slice4, slice2)
slice4[1] = 567
fmt.Printf("slice1 ==> %v \n", slice1)
fmt.Printf("slice2 ==> %v \n", slice2)
fmt.Printf("slice4 ==> %v \n", slice4)
ArrayChunk 数组切割
func ArrayChunkString(s []string, size int) [][]string {
if size < 1 {
panic("size: cannot be less than 1")
}
length := len(s)
chunks := int(math.Ceil(float64(length) / float64(size)))
var n [][]string
for i, end := 0, 0; chunks > 0; chunks-- {
end = (i + 1) * size
if end > length {
end = length
}
n = append(n, s[i*size:end])
i++
}
return n
}
func ArrayChunkInt(i []int, size int) [][]int {
batches := make([][]int, 0, (len(i)+size-1)/size)
for size < len(i) {
i, batches = i[size:], append(batches, i[0:size:size])
}
batches = append(batches, i)
return batches
}
ArrayReverse 数组反转
func ArrayReverseInt(i []int) []int {
for left, right := 0, len(i)-1; left < right; left, right = left+1, right-1 {
i[left], i[right] = i[right], i[left]
}
return i
}