英文:
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"}}}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论