What you want is auctually a map with default value that is not zero value, but a value ready to use, in this case, a made map.
Before going to the solution, there auctually is an issue about go here: https://github.com/golang/go/issues/3117
For reasons, Go now does not support to assign to a field of a struct if the struct is stored in a map.
To solve the issue, you need to use a pointer to that struct, and store the pointer in the map instead. So your data structure needs to be changed like:
type Base struct {
base map[int8]uint64
}
type Middle struct {
baseObjects map[int8]*Base
}
type Top struct {
middleObjects map[int8]*Middle
}
And to the core logic: a defualt value map. Go does not support that with plain maps, but we can extend it, using methods to wrap it around.
func (t Top) Get(i int8) *Middle {
x, ok := t.middleObjects[i]
if !ok {
v := NewMiddle()
t.middleObjects[i] = v
return v
}
return x
}
func (m Middle) Get(i int8) *Base {
x, ok := m.baseObjects[i]
if !ok {
v := NewBase()
m.baseObjects[i] = v
return v
}
return x
}
When we are trying to get a value, we first check if it exists. If not, we return a new constructed one, and if it did exist, return the value.
Usage:
t.Get(8).Get(9).base[10] = 14
Playground example: https://play.golang.org/p/0JSN0yjRPif