开发者

How do I declare an array(or equivalent) in Go

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 i开发者_运维技巧s there any alternative to make this work?

Sorry for my bad English.


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)


"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.


You can also be interested in a generic matrix package:

gomatrix

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜