Given the following:
type AStruct struct {
m_Map map[int]bool
}
In this case, an instance of AStruct
cannot be used until AStruct.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 of AStuct
is out there, waiting to generate a panic
.
I could make init()
private and declare an initialized bool
flag in the struct
set it true
in init()
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.