我是Golang的新手,我正在尝试使用底部的字符串列表初始化结构体结构。我希望能够以干净和可读的方式访问内部的值,但它不是单击。
例如,结构设置如下:
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
}
我正在初始化它:
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",},
},
},
},
},
},
},
}
然后,要访问任何字段,我必须执行以下操作:
func main() {
for user, _ := range users {
fmt.Println(users[user][0].instances[0].name)
}
}
必须有更好的方法吗?这里运行(但粗略)代码示例:http://play.golang.org/p/9M8pyBnMPB
答案 0 :(得分:0)
只需编写功能。
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
}
然后这与您的代码具有相同的效果:
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
如果访问事情变得复杂..更多功能:
func (u user) InstanceName(i int) string {
return u.instances[i].name
}
或考虑重新修改数据结构。