英文:
Nested array of struct initialization: how to do if constructors for both struct are available?
问题
新手学习golang。我有两个结构体类型(称为Inner和Outer),并且为它们各自编写了构造函数,我想要使用它们。Outer结构体“拥有”一个Inner结构体的二维数组。我该如何在Outer结构体的构造函数中使用Inner类型的构造函数,来初始化Inner的数组?
type Inner struct {
val int
}
func newInner(val int) *Inner {
i := new(Inner)
i.val = val
return i
}
type Outer struct {
members [][]Inner
row int
col int
}
func newOuter(row int, col int) *Outer {
o := new(Outer)
o.row = row
o.col = col
// 如何使用Inner的构造函数初始化一个大小为[row][col]的二维数组?
o.members = make([][]Inner, row)
for i := 0; i < row; i++ {
o.members[i] = make([]Inner, col)
for j := 0; j < col; j++ {
o.members[i][j] = *newInner(0) // 使用Inner的构造函数初始化Inner结构体
}
}
return o
}
希望对你有帮助!
英文:
New to golang. I have two struct types (called Inner, Outer), and have constructors for each of them that I would like to use. Outer struct "has-a" 2d array of Inner struct. How do I use the constructor for the inner type inside the constructor of outer struct, to initialize the array of inner?
<!-- begin snippet: js hide: false console: true babel: false -->
<!-- language: lang-js -->
type Inner struct {
val int
}
func newInner(val int) *Inner {
i:=new(Inner)
i.val=val
return i
}
type Outer struct {
members [][]Inner
row int
col int
}
func newOuter(row int, col int) *Outer {
o:=new(Outer)
o.row=row
o.col=col
//how do I initialize a 2d array of size [row][col] and
//using the constructor for inner?
return o
}
<!-- end snippet -->
答案1
得分: 1
你可以使用make
函数,并通过迭代矩阵来进行初始化。
defaultInner := newInner(100)
o.members = make([][]Inner, o.row)
for i := 0; i < o.row; i++ {
o.members[i] = make([]Inner, o.col)
for j := 0; j < o.col; j++ {
o.members[i][j] = *defaultInner
}
}
这段代码的作用是使用make
函数创建一个二维切片,并通过迭代矩阵的行和列来初始化切片中的元素。在每个位置上,都将默认的defaultInner
赋值给切片中的元素。
英文:
You can use make
and then iterate through the matrix to initialize it.
defaultInner := newInner(100)
o.members = make([][]Inner, o.row)
for i := 0; i < o.row; i++ {
o.members[i] = make([]Inner, o.col)
for j := 0; j < o.col; j++ {
o.members[i][j] = *defaultInner
}
}
答案2
得分: 1
func newOuter(row int, col int) *Outer {
o := new(Outer)
o.row = row
o.col = col
//如何初始化一个大小为[row][col]的二维数组,并使用内部构造函数?...
//
//下面是一种方法:
o.members = make([][]Inner, row)
for i := 0; i < row; i++ {
memberRow := make([]Inner, col)
for j := 0; j < col; j++ {
memberRow[j] = *newInner(100)
}
o.members[i] = memberRow
}
return o
}
英文:
func newOuter(row int, col int) *Outer {
o:=new(Outer)
o.row=row
o.col=col
//how do I initialize a 2d array of size [row][col] and
//using the constructor for inner?...
//
//here's one way:
o.members = make([][]Inner, row)
for i := 0; i < row; i++ {
memberRow := make([]Inner, col)
for j := 0; j < col; j++ {
memberRow[j] = *newInner(100)
}
o.members[i] = memberRow
}
return o
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论