Given the following:
type AStruct struct {
m_Map map[int]bool
}
In this case, an instance ofAStruct
cannot be used untilAStruct.m_Map
is initialized:
m_Map=make(map[int]bool,100)
I have taken to writing an Init()
function for my structs in such cases:
func (s *AStruct) Init() {
s.m_Map=make(map[int]bool,100)
}
I don't particularly care for this design, because it requires(s *AStruct) Init()
to be public and mandates that clients call it explicitly before using an instance of AStuct
- in the interim an unusable instance ofAStuct
is out there, waiting to generate apanic
.
I could make init()
private and declare an initialized bool
flag in thestruct
set ittrue
ininit()
after everything is initialized and check in each method:
func (s *AStruct) DoStuff {
if !s.initialized {
s.init()
}
s.m_Map[1]=false
s.m_Map[2]=true
}
But this is awkward and adds superfluous code.
Is there is standard way of handling this in Go? One that guarantees m_Map will be initialized without relying on clients to call Init()
?