Back to questions
JuniorTheoryCommon
What happens when this program is built and run?
package main
import "fmt"
func main() {
var p *int
fmt.Println(*p)
}Panic: runtime error: invalid memory address or nil pointer dereference
- Expecting
0, as when reading a missing key from a map:*preads theintat the address inp, and anilpointer has nointbehind it, so the program panics. - Expecting
<nil>: that is whatfmt.Println(p)would print;*pasks for the value behind the pointer, not the pointer itself.
- How would you change the program so that it prints
0without a panic? - How can a function guard against being handed a
nilpointer?