I am trying to assign values to a map that is initialized in the init func.
But panic occurs: assignment to entry in nil map
package main
type Object interface {
}
type ObjectImpl struct {
}
type Test struct{
collection map[uint64] Object
}
func (test Test) init(){
test.collection = make(map[uint64] Object)
}
func main() {
test := &Test{}
test.init()
test.collection[1]=&ObjectImpl{}
}
The function takes Test
as value, so it gets its own copy of it. All changes to test Test
will be gone when the function returns. Take Test
by pointer instead:
func (test *Test) init(){
test.collection = make(map[uint64] Object)
}
Note though, the struct Test
is exported, the method init
is not, therefore a user of your library could potentially create a Test
but not init it properly. It seems like the go community has established the convention of a freestanding NewType
method:
type test struct{
collection map[uint64] Object
}
function NewTest() *test {
return &test{
collection: make(map[uint64] Object),
}
}
This ensures a user can only obtain a test
by calling NewTest
and it will be initialized as intended.
You should use a pointer receiver for the init
method:
func (test *Test) init() { // use a pointer to test
test.collection = make(map[uint64] Object)
}
Without a pointer, you are initializing a map for a copy of the test
object. The actual test
object never gets an initialized map.