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?
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 theB
field, I would probably write something like:Playground
Output