排列数组类型的映射键并切片每个数组会为每次迭代提供相同的数组 [英] Ranging over map keys of array type and slicing each array gives the same array for each iteration

查看:40
本文介绍了排列数组类型的映射键并切片每个数组会为每次迭代提供相同的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在尝试将地图的int数组键添加到int slice的切片时,按预期进行范围和使用 arr [:] 切片数组无法正常工作.所得切片仅包含第一"片段的重复.键入地图(注释为循环).但是,将数组键复制到另一个变量并切片新变量是可行的,并且所得的切片包含不同的映射键值.我想知道为什么需要复制.数组键 k 是不是在每次迭代时从映射中复制为新数组?我不知道在哪里可以找到有关此行为的文档,因此不胜感激链接和资源:-)

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[:])
}

推荐答案

由于地图键类型是数组,因此分配:

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

for k,_ := range ans {

将为每次迭代重写 k .这将重写数组 k 的内容.切片 k [:] 指向 k 作为基础数组,因此所有以 k 作为其基础数组的切片也将被覆盖

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.

这篇关于排列数组类型的映射键并切片每个数组会为每次迭代提供相同的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆