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.
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"}}}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With