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

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

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>
  • 写回答

2条回答 默认 最新

  • 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
            }
        }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog