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?
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
}
</div>
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
}
}
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
}