Golang invalid memory address or nil pointer dereference
06 April, 2021
Go: panic: runtime error: invalid memory address or nil pointer dereference
Problem statement
Sample code
type Calculate struct {
X, Y int64
}
func (c *Calculate) Sum() int64 {
return c.X + c.Y
}
func main() {
var cal *Calculate // Initialize cal to <nil>
fmt.Println("SUM =", cal.Sum()) // calling method on <nil> creates panic
}
}
Running code
go run main.go
Output:
panic: runtime error: invalid memory address or nil pointer dereference
[signal SIGSEGV: segmentation violation code=0x1 addr=0x0 pc=0x497783]
goroutine 1 [running]:
main.(*Calculate).Sum(...)
/tmp/sandbox800773077/prog.go:12
main.main()
/tmp/sandbox800773077/prog.go:17 +0x23
Why is issue:
The uninitialized pointer "cal" in the main function is nil, and so can’t call method on the nil pointer. If "cal" is nil, an attempt to evaluate "*cal" will cause a run-time panic.
Solution
func main() {
var cal *Calculate = new(Calculate) // Initialize cal to &{0 0}
fmt.Println("SUM".cal.Sum()) // calling method cal Worked
}
Output : SUM = 0