I'm new to Golang, and I'm trying to initialize a struct of structs with a list of strings at the bottom. I'd like to be able to access the values inside in a clean and readable way, but it isn't clicking.
for example, the struct setup is as follows:
type config struct {
// a config can have many replicas
configName string
replicas []string
}
type instance struct {
// an instance can have many configs
name string
configs []config
}
type user struct {
// a user can have up to two instances
instances []instance
}
And I'm initializing it like so:
var users = map[string][]user{
"user-1": []user {
{
[]instance {
{
"instance-1",
[]config {
{
"some-config-1",
[]string{"xx", "yy", "zz",},
},
},
},
},
},
},
"user-2": {
{
[]instance {
{
"instance-2",
[]config {
{
"some-config-2",
[]string{"xx", "yy", "zz",},
},
},
},
},
},
},
}
Then, to access any of the fields, I have to do gross stuff like:
func main() {
for user, _ := range users {
fmt.Println(users[user][0].instances[0].name)
}
}
There must be a better way? Running (but gross) code example here: http://play.golang.org/p/9M8pyBnMPB
Just write functions.
func NewInstance(n string, confs ...config) instance {
var i instance
i.name = n
i.configs = confs
return i
}
func NewConfig(name string, reps ...string) config {
var c config
c.configName = name
c.replicas = reps
return c
}
func NewUser(ins ...instance) user {
var u user
u.instances = ins
return u
}
Then this has the same effect as your code:
var users map[string][]user
func main() {
users = make(map[string][]user)
u1_i1 := NewInstance("instance-1",
NewConfig("conf1", "xx", "yy", "zz"))
users["user-1"] = []user{NewUser(u1_i1)}
u2_i1 := NewInstance("instance-2",
NewConfig("conf2", "xx", "yy", "zz", "aa"))
users["user-2"] = []user{NewUser(u2_i1)}
for user, _ := range users {
fmt.Println(users[user][0].instances[0].name)
}
}
http://play.golang.org/p/okmBapuDWj
If accessing things gets complicated.. more functions:
func (u user) InstanceName(i int) string {
return u.instances[i].name
}
or consider reworking your data structures.