// why does the printout of ‘array’ fill all slots with only the last entry appended?
package main
import “fmt”
var array int
var pos int
func main() {
pos = append(pos, 0)
pos = append(pos, 0)
array = make(int, 0, 100)
count := 0
for i := 0; i < 2; i++ {
for j := 0; j < 2; j++ {
pos[0] = j
pos[1] = 0
fmt.Println(“i=”, i, “j=”, j, “count=”, count, “pos=”, pos)
array = append(array, pos)
fmt.Println(“appending pos=”, pos, “to array”)
fmt.Println(“just added”, array[count])
count++
}
}
fmt.Println(“size is”, len(array))
fmt.Println(“array”, array)
}
// thanks!
A slice is a reference, so when you create the slice pos and add two elements it is created only one time and when you assign new values your are assigned to the same address.
var pos []int // Here pos is null pos = append(pos, 0) pos = append(pos, 0)
So you will need to created pos slice inside the loop.
for j := 0; j < 2; j++ { pos := make([]int, 2) pos[0] = j pos[1] = 0 fmt.Printf("address of pos %p \n", &pos) fmt.Println("i=", i, "j=", j, "count=", count, "pos=", pos)
array = append(array, pos)
fmt.Println("appending pos=", pos, "to array")
fmt.Println("just added", array[count])
count++
}
To check the address of your slice just
fmt.Printf("address of pos %p \n", &pos)
Because the slice itself is a pointer, you’re actually operating on the same pointer in the pos.
// array = append(array, pos)
array = append(array, []int{pos[0], pos[1]})
// or
array = append(array, append(make([]int, 0, len(pos)), pos...))
// or other...