本文介绍了嵌套结构初始化文字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



  type A struct {
MemberA string
}

type B struct {
A
MemberB string
}

...

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

编译时给了我:结构字面量中的未知B字段'MemberA'

如何初始化MemberA(从父类结构),当我提供像这样的字面结构成员值吗?

解决方案

初始化匿名结构只知道它的类型名称(在你的情况下 A )。
在存在
实例后,与结构相关的成员和函数只会被导出到外部。



您必须提供一个有效的实例 A 来初始化 MemberA

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

编译器错误

确切地说:没有 MemberA ,因为它仍然在 A 中,而不是在 B 中。事实上,
B 永远不会有 MemberA ,它将始终保持在 A 。能够访问 B 实例上的 MemberA
只是语法糖。


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\n", 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?

解决方案

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 theinstance exists.

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

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

The compiler error

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 MemberAon an instance of B is only syntactic sugar.

这篇关于嵌套结构初始化文字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

05-27 07:05