ceving
ceving

Reputation: 23754

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

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.

Upvotes: 5

Views: 131

Answers (1)

ANisus
ANisus

Reputation: 77925

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

Upvotes: 3

Related Questions