当尝试将映射的 int 数组键添加到 int 切片切片时,范围和使用arr[:]切片数组无法按预期工作。结果切片仅包含映射中“第一个”键的副本(注释掉 for 循环)。但是,将数组键复制到另一个变量并对新变量进行切片是可行的,结果切片包含不同的映射键值。我想知道为什么需要复制。数组键不是k在每次迭代时从映射中复制为新数组吗?我不知道在哪里可以找到有关此行为的文档,并希望获得链接和资源 :-)
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[:])
}
慕哥9229398
相关分类