Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Missing type in composite literal

Tags:

struct

go

type A struct {
    B struct {
        Some string
        Len  int
    }
}

Simple question. How to initialize this struct? I would like to do something like this:

a := &A{B:{Some: "xxx", Len: 3}} 

Expectedly I'm getting an error:

missing type in composite literal

Sure, I can create a separated struct B and initialize it this way:

type Btype struct {
    Some string
    Len int
}

type A struct {
    B Btype
}

a := &A{B:Btype{Some: "xxx", Len: 3}}

But it not so useful than the first way. Is there a shortcut to initialize anonymous structure?

like image 648
tacobot Avatar asked Jul 28 '13 21:07

tacobot


3 Answers

The assignability rules are forgiving for anonymous types which leads to another possibility where you can retain the original definition of A while allowing short composite literals of that type to be written. If you really insist on an anonymous type for the B field, I would probably write something like:

package main

import "fmt"

type (
        A struct {
                B struct {
                        Some string
                        Len  int
                }
        }

        b struct {
                Some string
                Len  int
        }
)

func main() {
        a := &A{b{"xxx", 3}}
        fmt.Printf("%#v\n", a)
}

Playground


Output

&main.A{B:struct { Some string; Len int }{Some:"xxx", Len:3}}
like image 199
zzzz Avatar answered Oct 12 '22 04:10

zzzz


do it this way:

type Config struct {
    Element struct {    
        Name string 
        ConfigPaths []string 
    } 
}
config = Config{}
config.Element.Name = "foo"
config.Element.ConfigPaths = []string{"blah"}
like image 31
Michal K Avatar answered Oct 12 '22 03:10

Michal K


This is simpler imo:

type A struct {
    B struct {
        Some string
        Len  int
    }
}

a := A{
    struct {
        Some string
        Len  int
    }{"xxx", 3},
}
fmt.Printf("%+v", a)
like image 2
rogamba Avatar answered Oct 12 '22 05:10

rogamba