Ranging over map keys of array type and slicing each array gives the same array for each iteration

前端 未结 1 521
臣服心动
臣服心动 2021-01-29 08:42

When trying to add int array keys of a map to a slice of int slices, ranging and using arr[:] to slice array doesn\'t work as expected. The resultant slice contains

相关标签:
1条回答
  • 2021-01-29 09:11

    Since the map key type is an array, the assignment:

    for k,_ := range ans {
    

    will rewrite k for every iteration. This will rewrite the contents of the array k. The slice k[:] points to k as the underlying array, so all the slices with k as their underlying array will be overwritten as well.

    Copy the array for each iteration, as you did. That will create separate arrays for the slices you append.

    0 讨论(0)
提交回复
热议问题