Given the following:
type AStruct struct {
m_Map map[int]bool
}
In this case, an instance ofAStructcannot be used untilAStruct.m_Mapis 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 ofAStuctis out there, waiting to generate apanic.
I could make init() private and declare an initialized boolflag in thestruct set ittrueininit()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()?
The standard for a type Foo is to write a constructor NewFoo() which is not a method on the type, but returns a value of type Foo (or *Foo). Then as long as all instances of Foo are generated through a call to NewFoo() (and not through a literal or a call to the new() builtin) then you're safe.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With