I have the following data structure. It a chain of a struct that each has map[string]T. Basically I'm serializing a complex yaml file to a data structure. I have a two version that does work but one doesn't and it not clear for me why? Based on my understand Go compiler is very smart so it supposes to figure out where object needs to be allocated.
Please consider a code below.
type UserData struct {
Username string
Password string
}
type Groups struct {
users map[string] UserData
}
type Cluster struct {
Group map[string] Groups
}
type Director struct {
Cluster map[string]Cluster
}
//... I removed other add function.. Same semantic each add X function
// check if a map is nil call make(map[string]T) add a key)
// add a key with struct (where struct hold nil map)
func (c *Cluster) AddGroup(groupName string) Group {
if c.Group == nil {
c.Group = make(map[string]Groups)
}
c.Group[groupName] = Groups {}
group, _ := c.Group[groupName]
return group
}
func (p *Director) AddCluster(clusterName string) Cluster {
if p.Cluster == nil {
p.Cluster = make(map[string]Cluster)
}
p.Cluster[clusterName] = Cluster{}
cluster, _ := p.Cluster[clusterName]
return cluster
// does a compiler here allocate an object on the
// stack for Cluster {} and it goes out of a scope ?
}
if a caller does something like
var p = Director{}
cluster := p.AddCluster("Test Cluster")
cluster.AddGroup("Test Group")
It doesn't work -- First call does create a map and puts a value but the second call doesn't work. The key is never added to the second map.
In a version that does work, I created a constructor function that does(same semantic in each method). For example, version that does work below. (I use here the same semantic I usually do with C++ and other languages)
func NewCluster() *Cluster {
var cluster = Cluster{}
cluster.Group = make(map[string]Groups)
return &cluster
}
func (p *Director) AddCluster(clusterName string) {
if p.Cluster == nil {
p.Cluster = make(map[string]Cluster)
}
p.Cluster[clusterName] = *NewCluster()
}
I guess when you get used to one language compiler magic makes life harder :)