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

强颜欢笑 提交于 2021-02-05 12:16:34

问题


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 only duplicates of the "first" key in the map(commented out for loop). However, copying the array key to another variable and slicing the new variable works, and the resultant slice contains distinct map key values. I wonder why the copying is necessary. Isn't k, the array key, copied from the map as a new array at each iteration? I don't know where to find documentation regarding this behavior, and would appreciate links and resources :-)

ansSlice := [][]int{}

//ans is a map with [3]int key type

/* For some reason, this doesn't work, and appends values from the same array to ansSlice
for k, _ := range ans {
    ansSlice = append(ansSlice, k[:])
}*/

// however, this works
for k, _ := range ans {
    key := k
    ansSlice = append(ansSlice, key[:])
}

回答1:


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.



来源:https://stackoverflow.com/questions/63361128/ranging-over-map-keys-of-array-type-and-slicing-each-array-gives-the-same-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!