问题
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