英文:
Initialize struct with array of n elements
问题
我正在尝试在Go语言中实现一个矩阵。我有一个结构体:
type Matrix struct {
n, m int
rows [][]int
}
目前,rows
只是一个切片的切片。由于我知道我想要存储的每个数组的大小,所以似乎我应该能够使用大小为n和m的数组。在给n和m赋值之前,有没有一种正确的方法来声明rows
为一个大小为n的数组,其中包含大小为m的数组?
英文:
I am trying to implement a matrix in Go. I have a struct:
type Matrix struct {
n, m int
rows [][]int
}
Currently, rows is just a slice of slices. Since I know the size of each array I want to store, it seems like I should be able to use arrays of size n and m. Is there a right way to declare rows to be an array of size n containing arrays of size m before n and m are given values?
答案1
得分: 1
不。数组需要在编译时固定大小。如果 n 和/或 m 只在运行时才知道,你需要使用切片/切片的方式。
英文:
No. Array need fixed, constant size at compile time. If n and/or m are known only at runtime you'll have to go with a slice/slice-of-slices.
答案2
得分: 0
你可以声明大小:http://play.golang.org/p/BPharxQYfL
上面的简单示例显示了如何将Matrix.row的大小归零,以符合类型声明中指定的大小。
英文:
You can declare the size: http://play.golang.org/p/BPharxQYfL
The simple example above shows how Matrix.row is zero'd out to the size indicated in the type declaration.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论