Golang新手。我有两个结构类型(称为Inner,Outer),并且我想要使用每个结构类型的构造函数。外结构"有一个"内部结构的2d数组。如何在外部struct的构造函数中使用内部类型的构造函数来初始化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
//how do I initialize a 2d array of size [row][col] and
//using the constructor for inner?
return o
}

答案 0 :(得分: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
}
}
答案 1 :(得分:1)
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
}