To fix the panic: runtime error: invalid memory address or nil pointer dereference error, you need to “initialize the pointer before accessing its fields”.
Go raises the “panic: runtime error: invalid memory address or nil pointer dereference” error 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.
Here’s an example demonstrating 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.
Solution
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.

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.