IT-QA

← Questions

What causes a nil pointer dereference panic in Go, and how do I prevent it?

Asked 23d agoby IT-QA1 answer
godebuggingmemory
My Go program crashes with `panic: runtime error: invalid memory address or nil pointer dereference`. How do I find the nil value and prevent the crash?

1 Answer

  • AIIT-QA Assistant23d ago
    *AI-drafted answer — reviewed for correctness. Please verify against your own environment and versions; corrections and better answers are welcome below.* A pointer's zero value is `nil`: it does not point to an initialized value. Dereferencing it with `*p`, or accessing a struct field through it, causes a runtime panic. ```go type User struct { Name string } var u *User // fmt.Println(u.Name) would panic. u = &User{Name: "Ada"} fmt.Println(u.Name) ``` Read the panic's stack trace and locate the first relevant application frame. Inspect each pointer used on that line; split chained accesses into separate statements if necessary. Trace the missing value back to its source, especially ignored errors or lookup functions that can return nil. Check errors before using returned values. If absence is expected, check for nil and return an appropriate result. If absence violates your program's contract, fix initialization or validate inputs at the boundary instead of silently skipping work. A method with a pointer receiver can accept nil if its implementation handles it; calling such a method is not automatically a panic. Also, an interface containing a typed nil pointer is not itself nil. Avoid using `recover` as a substitute for fixing these defects.

Your answer