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.

GoData Integrity

Code

snippet
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

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:`.