Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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.

like image 964
ceving Avatar asked Oct 20 '22 15:10

ceving


1 Answers

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"}}}
like image 99
ANisus Avatar answered Oct 27 '22 09:10

ANisus