First of all, thanks a lot for your solution andrey!
Let me explain what I'm trying to do --- I'm trying to covert my struct
into map with github.com/fatih/structs
https://groups.google.com/d/msg/golang-nuts/eyYnelZF1zo/Z0IPBcArCwAJ
but the following gave me "panic: not struct"
type Server struct {
Name string
ID int32
Enabled bool
}
s := []Server{
{
Name: "Arslan",
ID: 123456,
Enabled: true,
},
{
Name: "Arslan",
ID: 123456,
Enabled: true,
},
}
m := structs.Map(s)
That's why I'm wrapping a slice under a struct to make it works *for my
"map[string]interface {}" data*.
On Tue, Aug 22, 2017 at 10:48 AM, Konstantin Khomoutov <[email protected]>
wrote:
> On Tue, Aug 22, 2017 at 07:38:03AM -0700, Tong Sun wrote:
>
> > How to initialize a go struct like the following?
> >
> > type Server struct {
> > Name string
> > ID int32
> > Enabled bool
> > }
>
> This type definition looks pretty much OK.
>
> > s := struct {
> > Servers []Server{
> > {
> > Name: "Arslan",
> > ID: 123456,
> > Enabled: true,
> > },
> > {
> > Name: "Arslan",
> > ID: 123456,
> > Enabled: true,
> > },
> > }
> > }
>
> ...and this is a very strange idea: struct types contain fixed number
> of named fields, so
>
> s := struct{
> // what's this?
> }
>
> > That didn't work so I tried to introduce a new type to capture it:
> >
> > type Server struct {
> > Name string
> > ID int32
> > Enabled bool
> > }
> > type Servers struct {
> > servers []Server
> > }
>
> This is possible but arguably don't needed.
> If all you need is merely a slice of Server instances,
> just use it.
>
> > s := &Servers{servers: []Server{
> > {
> > Name: "Arslan",
> > ID: 123456,
> > Enabled: true,
> > },
> > {
> > Name: "Arslan",
> > ID: 123456,
> > Enabled: true,
> > },
> > }
> >
> > but that failed also.
> >
> > What's the correct way?
>
> In the simplest case:
>
> s := []Server{
> Server{
> Name: "Arslan",
> ID: 123456,
> Enabled: true,
> },
> ...
> }
>
> If you need your nested structs, then
>
> s := Servers{
> servers: []Server{
> Server{
> Name: "Arslan",
> ID: 123456,
> Enabled: true,
> },
> ...
> }
> }
>
--
You received this message because you are subscribed to the Google Groups
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email
to [email protected].
For more options, visit https://groups.google.com/d/optout.