How to Fix panic: assignment to entry in nil map Error in Go

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.

Reproduce the 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 the error?

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.

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.