Go中内部结构文字的正确语法是什么?

cev*_*ing 5 go

我想以字面形式初始化A及其所有内部结构.

package main

import "fmt"

type A struct {
    B struct {
        C struct {
            D string
        }
    }
}

func main() {
    x := A{B{C{D: "Hello"}}}
    y := A{B.C.D: "Hello"}

    fmt.Println(a)
}
Run Code Online (Sandbox Code Playgroud)

什么是正确的语法?

我需要这个来构建XML编组的结构.

ANi*_*sus 3

构建复合文字时,必须声明结构的文字类型。

如果仅使用匿名类型,这会变得相当乏味。相反,您应该考虑单独声明每个结构:

package main

import "fmt"

type A struct {
    B B
}

type B struct {
    C C
}

type C struct {
    D string
}

func main() {
    x := A{B: B{C: C{D: "Hello"}}}
    // x := A{B{C{"Hello"}}} // Without using keys

    fmt.Println(x)
}
Run Code Online (Sandbox Code Playgroud)

编辑:

如示例所示,使用匿名类型初始化结构将如下所示:

x := A{struct{ C struct{ D string } }{struct{ D string }{"Hello"}}}
Run Code Online (Sandbox Code Playgroud)