// 创建一个位数为[dx][dy]的切片 a := make([][]uint8, dx) for i := range a { a[i] = make([]uint8, dy) }
第二种方式,不允许第二维大小有所变化,因为改变了就会有可能覆盖:
1 2 3 4 5 6 7 8
// Allocate the top-level slice, the same as before. picture := make([][]uint8, YSize) // One row per unit of y. // Allocate one large slice to hold all the pixels. pixels := make([]uint8, XSize*YSize) // Has type []uint8 even though picture is [][]uint8. // Loop over the rows, slicing each row from the front of the remaining pixels slice. for i := range picture { picture[i], pixels = pixels[:XSize], pixels[XSize:] }
funcmain() { pow := []int{4, 1, 5} for _, value := range pow { fmt.Printf("%d\n", value) } // 只有一个值只会得到下标 for idx := range pow { fmt.Printf("%d\n", pow[idx]) } }
切片的技巧
优雅地往slice插入一个value:
1 2 3 4 5 6 7 8 9 10 11 12 13
// Insert inserts the value into the slice at the specified index, // which must be in range. // The slice must have room for the new element. funcInsert(slice []int, index, value int) []int { // Grow the slice by one element. slice = slice[0 : len(slice)+1] // Use copy to move the upper part of the slice out of the way and open a hole. copy(slice[index+1:], slice[index:]) // Store the new value. slice[index] = value // Return the result. return slice }
优雅地合并两个切片:
1 2 3 4
a := []string{"John", "Paul"} b := []string{"George", "Ringo", "Pete"} a = append(a, b...) // equivalent to "append(a, b[0], b[1], b[2])" // a == []string{"John", "Paul", "George", "Ringo", "Pete"}
优雅地copy:
1 2 3 4
b = make([]T, len(a)) copy(b, a) // or b = append([]T(nil), a...)
cut,优雅地删除掉slice中的某一个区间:
1 2 3 4 5 6 7 8 9
// 普通版,对于元素为指针或者结构中含有指针,会存在内存泄漏,因为被删掉的元素仍属于slice a = append(a[:i], a[j:]...)
// 升级版,将指针设为nil,减少了内存泄漏,但是还是有元素属于slice copy(a[i:], a[j:]) for k, n := len(a)-j+i, len(a); k < n; k++ { a[k] = nil// or the zero value of T } a = a[:len(a)-j+i]
filter:
1 2 3 4 5 6 7 8 9 10
funcfilter(a []int) []int { n := 0 for _, x := range a { if keep(x) { a[n] = x n++ } } a = a[:n] }
reverse:
1 2 3 4
for i := len(a)/2-1; i >= 0; i-- { opp := len(a)-1-i a[i], a[opp] = a[opp], a[i] }
shuffling:
1 2 3 4 5 6 7
for i := len(a) - 1; i > 0; i-- { j := rand.Intn(i + 1) a[i], a[j] = a[j], a[i] }