du8791069
du8791069
2016-11-08 05:25
浏览 185
已采纳

嵌套的结构体初始化数组:如果两个结构体的构造函数都可用,该怎么办?

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>

图片转代码服务由CSDN问答提供 功能建议

golang的新手。 我有两种结构类型(称为内部,外部),并且每种类型都有要使用的构造函数。 外部结构“具有-a”内部结构的二维数组。 如何在外部struct的构造函数内部使用内部类型的构造函数来初始化内部的数组?

  type内部结构{
 
 val int 
 
} 
 
 
 
func newInner(val int)*内部{
 
i:  = new(Inner)
 
 i.val = val 
 
 return i 
 
} 
 
 
 
 
 
type外层结构{
 
成员[] [] Inner  
 
 row int 
 
 col int 
 
} 
 
 
 
func newOuter(row int,col int)*外部{
 
o:= new(Outer)
 
  o.row = row 
 
 o.col = col 
 
 //如何初始化大小为[row] [col]和
 
的二维数组//使用内部构造函数?
  
返回o 
 
}   
 
  
 
  
 
 
 
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

2条回答 默认 最新

  • dongshuohuan5291
    dongshuohuan5291 2016-11-08 05:53
    已采纳

    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
            }
        }
    
    点赞 评论
  • duanguan5922
    duanguan5922 2016-11-08 06:51
    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  
    }
    
    点赞 评论

相关推荐