英文:
How can I re-create this Javascript array structure in Go?
问题
我有一个JavaScript数组,我该如何在Go中重新创建它?我完全不知道如何创建这么多嵌套的切片或数组。
var goArray = [][]interface{}{
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
[]interface{}{},
}
JSON输出:
[[[],[],[],[],[]],[[],[],[],[],[]]]
谢谢!
英文:
I have this Javascript array, how can I recreate it in Go? I'm completely lost on how to create so many nested slices or arrays.
var jsArray = [
[
[],
[],
[],
[],
[],
],
[
[],
[],
[],
[],
[]
]
];
JSON output:
[[[],[],[],[],[]],[[],[],[],[],[]]]
Thank you!
答案1
得分: 2
假设你要存储在当前的JS数组中的值如下所示:
var jsArray = [
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10]
],
[
[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20]
]
];
相同的值可以用Golang切片来存储,如下所示:
goSlice := [][][]int{
{
[]int{1, 2},
[]int{3, 4},
[]int{5, 6},
[]int{7, 8},
[]int{9, 10},
},
{
[]int{11, 12},
[]int{13, 14},
[]int{15, 16},
[]int{17, 18},
[]int{19, 20},
},
}
上述切片的输出如下所示:
[[[1 2] [3 4] [5 6] [7 8] [9 10]] [[11 12] [13 14] [15 16] [17 18] [19 20]]]
这与jsArray
的结构相同。
如果你想使用数组而不是切片,可以这样定义:
goArray := [2][5][2]int{
{
[2]int{1, 2},
[2]int{3, 4},
[2]int{5, 6},
[2]int{7, 8},
[2]int{9, 10},
},
{
[2]int{11, 12},
[2]int{13, 14},
[2]int{15, 16},
[2]int{17, 18},
[2]int{19, 20},
},
}
希望这对你有所帮助。
英文:
Let's assume that the values that you will store in your current JS array will look like this
var jsArray = [
[
[1, 2],
[3, 4],
[5, 6],
[7, 8],
[9, 10]
],
[
[11, 12],
[13, 14],
[15, 16],
[17, 18],
[19, 20]
]
];
The same values can be stored in the Golang slices like this
goSlice := [][][]int{
{
[]int{1, 2},
[]int{3, 4},
[]int{5, 6},
[]int{7, 8},
[]int{9, 10},
},
{
[]int{11, 12},
[]int{13, 14},
[]int{15, 16},
[]int{17, 18},
[]int{19, 20},
},
}
The output for the above slice looks like this
> [[[1 2] [3 4] [5 6] [7 8] [9 10]] [[11 12] [13 14] [15 16] [17 18] [19
> 20]]]
which is identical to the jsArray
structure.
Instead of slices if you want to use array than you can use the define it like this
goArray := [2][5][2]int{
{
[2]int{1, 2},
[2]int{3, 4},
[2]int{5, 6},
[2]int{7, 8},
[2]int{9, 10},
},
{
[2]int{11, 12},
[2]int{13, 14},
[2]int{15, 16},
[2]int{17, 18},
[2]int{19, 20},
},
}
Hope this will help you.
答案2
得分: 0
尝试这个:
func main() {
var jsArray [2][5][0]int
fmt.Println(jsArray)
}
你可以创建嵌套的切片,并从外到内描述它包含的每个切片的长度。
https://www.tutorialspoint.com/go/go_multi_dimensional_arrays.htm
英文:
Try this:
func main() {
var jsArray [2][5][0]int
fmt.Println(jsArray)
}
You can create your nested slice and describe the length of each slice it contains going from the outside in.
https://www.tutorialspoint.com/go/go_multi_dimensional_arrays.htm
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论