Curriculum Types & methods Nil & zero values exercise 3 · mcq
Nil & zero values
THE classic Go gotcha. Consider:
``go
type Error interface { Error() string }
type MyErr struct{}
func (m *MyErr) Error() string { return "my error" }
func mightFail() Error {
var p *MyErr // p is a nil *MyErr
return p // returned as an Error interface
}
e := mightFail()
fmt.Println(e == nil)
``
What does this print?
About this theme
Every type has a zero value — what an uninitialised variable of that type holds. For numbers: 0. For strings: "". For bools: false. For pointers, interfaces, maps, slices, channels, and functions: nil. nil is *not* TypeScript's undefined — it's a typed absence, and conflating "nil pointer" with "nil interface" is one of the classic Go bugs.