How to Fix panic: runtime error: invalid memory address or nil pointer dereference

The “panic: runtime error: invalid memory address or nil pointer dereference” error occurs when you have a nil pointer in your code, and you are trying to get the value it points to. “ The error also occurs when you try to access a field, method, or value through a pointer that has not been initialized and is still nil.

You must “initialize the pointer before accessing its fields” to fix the error.

Diagram of error and solution

Diagram of runtime error - invalid memory address or nil pointer dereference

Reproduce the error

package main

import (
  "fmt"
)

type Student struct {
  Name string
}

func main() {
  var student *Student
  fmt.Println(student.Name)
}

Output

panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x2 addr=0x0 pc=0x10016c9d0]

goroutine 1 [running]:

In this example, we declared a variable person of type *Student (pointer to Student) but did not initialize it.

When we try to access the Name field of the Person struct through the person pointer, Go panics with the “invalid memory address or nil pointer dereference” error.

How to fix it?

package main

import (
  "fmt"
)

type Student struct {
  Name string
}

func main() {
  student := &Student{
    Name: "Krunal",
  }
  
  fmt.Println(student.Name)
}

Output

Krunal

In this updated example, we initialized the student pointer by assigning it the address of a new Student instance with the field Name set to “Krunal”.

There was no panic when we accessed the Name field, and the program worked as expected.

To avoid nil pointer dereference errors, always make sure that pointers are correctly initialized before accessing their fields, methods, or values.

That’s all!