I want to do something like(it's valid)
我想做一些事情,比如(它是有效的)
var myArray [9][3]int
but when I do
但是当我做
var myArray [someIntVariable][anotherOne]int
It can't be used(I know why, so I'm not asking this.) But is there any alternative to make this work?
它不能用(我知道为什么,所以我没有问这个)但是,有没有其他的办法可以让它发挥作用呢?
Sorry for my bad English.
对不起,我的英语不好。
3 个解决方案
#1
5
Does the following work for you?
下面这些对你有用吗?
func make2dArray(m, n int) [][]int {
myArray := make([][]int, m)
for i := range myArray {
myArray[i] = make([]int, n)
}
return myArray
}
var myArray := make2dArray(someIntVariable, anotherOne)
#2
1
"array" types in Go include the length as part of the type, so they are only good for things where the length is fixed at compile time (similar to "arrays" in C before C99). If you want "arrays" whose length is determined only at runtime (e.g. arrays in Java), what you really want is a "slice". mepcotterell's answer shows you how to create a slice of slices.
Go中的“数组”类型包括长度作为类型的一部分,因此它们只适用于在编译时固定长度的情况(类似于C99之前C中的“数组”)。如果您希望“数组”的长度仅在运行时确定(例如Java中的数组),那么您真正需要的是“切片”。mepcotterell的答案向您展示了如何创建切片。
#1
5
Does the following work for you?
下面这些对你有用吗?
func make2dArray(m, n int) [][]int {
myArray := make([][]int, m)
for i := range myArray {
myArray[i] = make([]int, n)
}
return myArray
}
var myArray := make2dArray(someIntVariable, anotherOne)
#2
1
"array" types in Go include the length as part of the type, so they are only good for things where the length is fixed at compile time (similar to "arrays" in C before C99). If you want "arrays" whose length is determined only at runtime (e.g. arrays in Java), what you really want is a "slice". mepcotterell's answer shows you how to create a slice of slices.
Go中的“数组”类型包括长度作为类型的一部分,因此它们只适用于在编译时固定长度的情况(类似于C99之前C中的“数组”)。如果您希望“数组”的长度仅在运行时确定(例如Java中的数组),那么您真正需要的是“切片”。mepcotterell的答案向您展示了如何创建切片。