这是我参与11月更文挑战的第27天,活动详情查看:2021最后一次更文挑战
二维切片
Go 的数组和切片是一维的。 要创建二维数组或切片,必须定义一个数组的数组或切片数组,如下所示:
type Transform [3][3]float64 // 一个 3x3 的数组,其实是包含多个数组的一个数组。
type LinesOfText [][]byte // 包含多个字节切片的一个切片。
因为切片是可变长度的,所以可以让每个内部切片的长度不同。 这是一种常见的情况,就像在我们的 LinesOfText 示例中一样:每行都有一个独立的长度。
text := LinesOfText{
[]byte("Now is the time"),
[]byte("for all good gophers"),
[]byte("to bring some fun to the party."),
}
有时需要分配 2D 切片,例如,在处理像素扫描线时可能会出现这种情况。 有两种方法可以实现这一点。 一种是独立分配每个slice; 另一种是分配单个数组并将各个切片指向其中。 使用哪个取决于您的程序。 如果切片可能会增长或缩小,则应单独分配以避免覆盖下一行; 如果没有,使用单个分配构造对象会更有效。 作为参考,这里是两种方法的草图。 首先,一次一行:
// 分配顶层slice Allocate the top-level slice.
picture := make([][]uint8, YSize) // One row per unit of y.
// 遍历行,为每一行都分配切片 Loop over the rows, allocating the slice for each row.
for i := range picture {
picture[i] = make([]uint8, XSize)
}
现在是一次分配,对行进行切片:
// 分配顶层slice,就和上面的例子一样 Allocate the top-level slice, the same as before.
picture := make([][]uint8, YSize) // One row per unit of y.
// 分配一个大容量的slice来存放所有的像素 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:]
}