duai5344 2013-10-11 19:09
浏览 17
已采纳

嵌套结构初始化文字

How can I do this:

type A struct {
    MemberA string
}

type B struct {
    A
    MemberB string
}

...

b := B {
    MemberA: "test1",
    MemberB: "test2",
}
fmt.Printf("%+v
", b)

Compiling that gives me: "unknown B field 'MemberA' in struct literal"

How can I initialize MemberA (from the "parent" struct) when I provide literal struct member values like this?

  • 写回答

2条回答 默认 最新

  • doumu4916 2013-10-11 19:26
    关注

    While initialization the anonymous struct is only known under its type name (in your case A). The members and functions associated with the struct are only exported to the outside after the instance exists.

    You have to supply a valid instance of A to initialize MemberA:

    b := B {
        A: A{MemberA: "test1"},
        MemberB: "test2",
    }
    

    The compiler error

    unknown B field 'MemberA' in struct literal

    says exactly that: there's no MemberA as it is still in A and not in B. In fact, B will never have MemberA, it will always remain in A. Being able to access MemberA on an instance of B is only syntactic sugar.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥17 pro*C预编译“闪回查询”报错SCN不能识别
  • ¥15 微信会员卡接入微信支付商户号收款
  • ¥15 如何获取烟草零售终端数据
  • ¥15 数学建模招标中位数问题
  • ¥15 phython路径名过长报错 不知道什么问题
  • ¥15 深度学习中模型转换该怎么实现
  • ¥15 HLs设计手写数字识别程序编译通不过
  • ¥15 Stata外部命令安装问题求帮助!
  • ¥15 从键盘随机输入A-H中的一串字符串,用七段数码管方法进行绘制。提交代码及运行截图。
  • ¥15 TYPCE母转母,插入认方向