What is the correct syntax for inner struct literals in Go?

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

What is the correct syntax for inner struct literals in Go?

问题

我想用字面形式初始化A及其内部结构。

package main

import "fmt"

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

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

	fmt.Println(a)
}

这是正确的语法。

我需要这样做来构建用于XML编组的结构体。

英文:

I would like to initialize A with all its inner structs in a literal form.

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)
}

What is the correct syntax?

I need this to build structs for XML marshaling.

答案1

得分: 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"}}} // 不使用键

	fmt.Println(x)
}

编辑:

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

x := A{struct{ C struct{ D string } }{struct{ D string }{"Hello"}}}
英文:

You must declare the literal type for structs when building Composite literals.

This makes it rather tedious if using only anonymous types. Instead, you should consider declaring each struct separately:

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)
}

Edit:

Initializing the struct with anonymous types as shown in your example, would look like this:

x := A{struct{ C struct{ D string } }{struct{ D string }{"Hello"}}}

huangapple
  • 本文由 发表于 2014年1月30日 17:55:03
  • 转载请务必保留本文链接:https://go.coder-hub.com/21453076.html
匿名

发表评论

匿名网友

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

确定