Two-Dimensional Slices Without Row Aliasing
Rows of a two-dimensional slice can share one backing array: append on one row overwrites the next row, so allocate each row independently.
Code
package main
import "fmt"
func main() {
rows, cols := 3, 4
// 错误示范:所有行切片指向同一个底层数组(row aliasing)
backing := make([]int, rows*cols)
shared := make([][]int, rows)
for i := range shared {
shared[i] = backing[i*cols : (i+1)*cols]
}
// 第 0 行 append 借用剩余容量,直接写进第 1 行的数据区
shared[0] = append(shared[0], 99)
fmt.Println("row1[0] after row0 append:", shared[1][0]) // 99
// 正确写法:每行独立 make,two-dimensional grid 互不干扰
grid := make([][]int, rows)
for i := range grid {
grid[i] = make([]int, cols)
}
grid[0] = append(grid[0], 99)
fmt.Println("row1[0] in independent grid:", grid[1][0]) // 0
}How it works
Two-Dimensional Slices Without Row Aliasing reduces to the function main.
The file repeats itself only inside for i := range shared.
Caveats
- Runs on what the toolchain ships by default — nothing extra needed.
Putting it to use
The signature doing the work here: func main()
Output lines are prefixed (row1[0] after row0 append:, row1[0] in independent grid:), so each printed line names the step that wrote it.
The core lines, annotated
for i := range shared {
shared[i] = backing[i*cols : (i+1)*cols]
}
for i := range grid {
grid[i] = make([]int, cols)
}
backing := make([]int, rows*cols)
Interactive Tools for This Topic
cURL to Python & Go ConverterTranslate curl CLI commands with headers, auth, JSON bodies, and timeouts into ready-to-run Python requests and Go net/http client code snippets.SRI Hash GeneratorGenerate Subresource Integrity (SRI) hashes from resource content using SHA-256, SHA-384, or SHA-512, and copy a ready-to-use script tag.
FAQ
- What does Two-Dimensional Slices Without Row Aliasing print when run?
- Run it as a complete program — the output lines carry labels such as `row1[0] after row0 append:`, `row1[0] in independent grid:`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.