To fix the runtime error panic: assignment to entry in nil map, you need to initialize the map using the make() function or use the constructor function before using it.
Go raises the panic: assignment to entry in nil map error when you try to assign a value to a map that hasn’t been initialized. In Go, a map needs to be initialized before it can be used to store key-value pairs. If you try to assign a value to an uninitialized map, you will encounter a runtime error.
See the below code that reproduces the runtime error.
package main
import "fmt"
type Student struct {
m map[string]string
}
func main() {
s := new(Student)
s.m["name"] = "Krunal"
fmt.Println(s.m)
}
Output
panic: assignment to entry in nil map
As mentioned earlier, the error occurs because the map s.m was not initialized before the assignment.
How to fix it?
There are two solutions to fix the panic.
- Using the make() function
- Using the constructor function
Fix 1: Using the make() function
To fix the error, initialize the map using the make() function.
package main
import "fmt"
type Student struct {
m map[string]string
}
func main() {
s := new(Student)
s.m = make(map[string]string)
s.m["name"] = "Krunal"
fmt.Println(s.m)
}
Output
map[name:Krunal]
Fix 2: Using the constructor function
You can also initialize the map within the Student struct by adding a constructor function.
package main
import "fmt"
type Student struct {
m map[string]string
}
func NewStudent() *Student {
return &Student{
m: make(map[string]string),
}
}
func main() {
s := NewStudent()
s.m["name"] = "Krunal"
fmt.Println(s.m)
}
Output
map[name:Krunal]
In this code example, we added a NewStudent() function that creates a new Student instance and initializes the map within the struct.
That’s it.

Krunal Lathiya is a Software Engineer with over eight years of experience. He has developed a strong foundation in computer science principles and a passion for problem-solving. In addition, Krunal has excellent knowledge of Distributed and cloud computing and is an expert in Go Language.