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 golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.