[英]Adding arrays (from a map) to a slice of slices in Go
I have a map with arrays for keys.我有一个 map 和 arrays 作为钥匙。 I want to add all of the keys/arrays to a slice of slices.我想将所有键/数组添加到一片切片中。
However, I am getting unexpected results.但是,我得到了意想不到的结果。
Code:代码:
package main
import "fmt"
func main() {
var finalResult [][]int
set := make(map[[2]int]int)
a, b, c := [2]int{1, 1}, [2]int{2, 2}, [2]int{3, 3}
set[a], set[b], set[c] = 1, 1, 1
fmt.Println("set: ", set)
for x := range set {
fmt.Println("\nfinalResult 0: ", finalResult)
fmt.Println("x: ", x[:])
finalResult = append(finalResult, x[:])
fmt.Println("finalResult 1: ", finalResult)
}
}
Output: Output:
set: map[[1 1]:1 [2 2]:1 [3 3]:1]
finalResult 0: []
x: [1 1]
finalResult 1: [[1 1]]
finalResult 0: [[2 2]]
x: [2 2]
finalResult 1: [[2 2] [2 2]]
finalResult 0: [[3 3] [3 3]]
x: [3 3]
finalResult 1: [[3 3] [3 3] [3 3]]
finalResult appears to be changing during the for loop? finalResult 似乎在 for 循环期间发生变化?
Can someone explain what is happening and how I can work around this issue?有人可以解释发生了什么以及我如何解决这个问题吗?
The problem is, that you append the x
local variable to the finalResult
, which is a pointer, so in every for loop, the x
will point to a new array in the memory. When you add this x
three times to the finalResult and print it, all the three x
will be points to the same memory address.问题是,你 append x
局部变量到finalResult
,它是一个指针,所以在每个 for 循环中, x
将指向 memory 中的一个新数组。当你将这个x
三次添加到 finalResult 并打印它,所有三个x
将指向相同的 memory 地址。 You have to copy the content where x
points in every loop to a new variable and add this to the finalResult.您必须将每个循环中x
指向的内容复制到一个新变量并将其添加到 finalResult。
package main
import "fmt"
func main() {
var finalResult [][]int
set := make(map[[2]int]int)
a, b, c := [2]int{1, 1}, [2]int{2, 2}, [2]int{3, 3}
set[a], set[b], set[c] = 1, 1, 1
fmt.Println("set: ", set)
for x := range set {
fmt.Println("\nfinalResult 0: ", finalResult)
fmt.Println("x: ", x[:])
a := make([]int, 2)
copy(a, x[:])
finalResult = append(finalResult, a)
fmt.Println("finalResult 1: ", finalResult)
}
}
But be aware, that ranging over a map will be always in random order, so your final result may change on every run.但请注意,map 的范围始终是随机顺序,因此您的最终结果可能会在每次运行时发生变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.