Unexpected behavior associated with multidimensional slices – Code Review

Greetings,

I detected a strange behavior when adding to slices:

Why do you do

package main

import (
	"fmt"
)

var (
	a  []int
	aa [][]int
)

func main() {
	a = make([]int, 4, 4)

	a[0] = 1
	a[1] = 2
	a[2] = 3
	a[3] = 4

	for i := 0; i < 4; i++ {
		a[0] = a[0] * 2
		a[1] = a[1] * 3
		a[2] = a[2] * 4
		a[3] = a[3] * 5

		aa = append(aa, []int{a[0], a[1], a[2], a[3]}) //[[2 6 12 20] [4 18 48 100] [8 54 192 500] [16 162 768 2500]]
		//aa = append(aa, a) //[[16 162 768 2500] [16 162 768 2500] [16 162 768 2500] [16 162 768 2500]]
		//aa = append(aa, a[:]) //[[16 162 768 2500] [16 162 768 2500] [16 162 768 2500] [16 162 768 2500]]
	}

	fmt.Println(aa)
}

result in

[[2 6 12 20] [4 18 48 100] [8 54 192 500] [16 162 768 2500],

However, instead of adding the whole piece

…
aa = append(aa, a)
…

result of

[[16 162 768 2500] [16 162 768 2500] [16 162 768 2500] [16 162 768 2500],

,

or even by copying the slice

…
aa = append(aa, a[:])
…

leads to this annoying behavior,

If He Not a bug, it’s a very bad feature at least!


Leave a Comment