将数组类型的映射键转换为二维切片
Converting map keys of type array to a 2D slice
我创建了一组 int 数组(以保持唯一的三元组),在执行一些步骤后需要 return 三元组列表。以下代码段仅显示了尝试进行此转换的部分,并且那里出现了问题。生成的 2D 切片正在复制三元组。
请帮我解决以下问题:
- 以下代码有什么问题?
- 执行此转换的正确方法应该是什么?
func main() {
setOfTriplets := make(map[[3]int]struct{})
// Oversimplified steps here just to show some usage of the setOfTriplets.
t1, t2 := [3]int{1, 2, 3}, [3]int{4, 5, 6}
setOfTriplets[t1] = struct{}{}
setOfTriplets[t2] = struct{}{}
// Convert the triplets to 2D slice (because that's what I need in the bigger problem)
matrix := make([][]int, 0, len(setOfTriplets))
for t, _ := range setOfTriplets {
// array to slice
st := t[:]
// PROBLEM: Something unkown happening here.
matrix = append(matrix, st)
}
// PROBLEM:
// Expected Output: [[1 2 3] [4 5 6]]
// Actual Output: [[1 2 3] [1 2 3]] and sometimes [[4 5 6] [4 5 6]]
fmt.Println(matrix)
}
您正在使用循环变量创建切片。循环变量是一个数组,每次迭代都会被覆盖。在第一次迭代期间,如果 tiplet 是 [1,2,3],它会被复制到 t
并从中创建一个切片。下一次迭代将用 [4,5,6]
覆盖 t
,这也将覆盖您之前添加到列表中的三元组。
要修复,请创建数组的副本:
for t, _ := range setOfTriplets {
t:=t // Copy the array
// array to slice
st := t[:]
matrix = append(matrix, st)
}
我创建了一组 int 数组(以保持唯一的三元组),在执行一些步骤后需要 return 三元组列表。以下代码段仅显示了尝试进行此转换的部分,并且那里出现了问题。生成的 2D 切片正在复制三元组。 请帮我解决以下问题:
- 以下代码有什么问题?
- 执行此转换的正确方法应该是什么?
func main() {
setOfTriplets := make(map[[3]int]struct{})
// Oversimplified steps here just to show some usage of the setOfTriplets.
t1, t2 := [3]int{1, 2, 3}, [3]int{4, 5, 6}
setOfTriplets[t1] = struct{}{}
setOfTriplets[t2] = struct{}{}
// Convert the triplets to 2D slice (because that's what I need in the bigger problem)
matrix := make([][]int, 0, len(setOfTriplets))
for t, _ := range setOfTriplets {
// array to slice
st := t[:]
// PROBLEM: Something unkown happening here.
matrix = append(matrix, st)
}
// PROBLEM:
// Expected Output: [[1 2 3] [4 5 6]]
// Actual Output: [[1 2 3] [1 2 3]] and sometimes [[4 5 6] [4 5 6]]
fmt.Println(matrix)
}
您正在使用循环变量创建切片。循环变量是一个数组,每次迭代都会被覆盖。在第一次迭代期间,如果 tiplet 是 [1,2,3],它会被复制到 t
并从中创建一个切片。下一次迭代将用 [4,5,6]
覆盖 t
,这也将覆盖您之前添加到列表中的三元组。
要修复,请创建数组的副本:
for t, _ := range setOfTriplets {
t:=t // Copy the array
// array to slice
st := t[:]
matrix = append(matrix, st)
}