嵌套结构初始化字面值

huangapple go评论92阅读模式
英文:

nested struct initialization literals

问题

你好!以下是翻译好的内容:

type A struct {
    MemberA string
}

type B struct {
    A       A
    MemberB string
}

...

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

编译时会报错:"在结构体字面值中未知的 B 字段 'MemberA'"。

当我像这样提供字面结构成员值时,如何初始化 MemberA(来自“父”结构体)?

英文:

How can I do this:

type A struct {
    MemberA string
}

type B struct {
    A 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?

答案1

得分: 45

在初始化时,匿名结构体只能通过其类型名称(在您的情况下为A)来识别。
结构体的成员和函数只有在实例存在之后才会对外部公开。

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

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

编译器错误

在结构体字面值中未知的 B 字段 'MemberA'

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

英文:

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.

答案2

得分: -4

问题出在在B中声明结构体A时。请在声明时指定名称,然后它就能正常工作。

package main

import "fmt"

type A struct {
    MemberA string
}

type B struct {
    MemA    A
    MemberB string
}

func main() {
    b := B{MemA: A{MemberA: "test1"}, MemberB: "test2"}
    fmt.Println(b.MemberB)
}
英文:

The problem is with declaring the struct A in B. Please specify the name along with declaration, then it works.

package main

import "fmt"

type A struct {
	MemberA string
}

type B struct {
	MemA    A
	MemberB string
}

func main() {
	b := B{MemA: A{MemberA: "test1"}, MemberB: "test2"}
	fmt.Println(b.MemberB)
}

huangapple
  • 本文由 发表于 2013年10月12日 03:09:31
  • 转载请务必保留本文链接:https://go.coder-hub.com/19325496.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定