Search⌘ K
AI Features

Puzzle 19 Explanation: Go Error

Explore the behavior of Go error interfaces in this lesson to understand why an interface may appear non-nil even if its underlying value is nil. Learn to identify common pitfalls with error handling and how to properly declare error variables to avoid such issues in Go programming.

We'll cover the following...

Try it yourself

Try executing the code below to see the result.

Go (1.16.5)
package main
import (
"fmt"
)
type OSError int
func (e *OSError) Error() string {
return fmt.Sprintf("error #%d", *e)
}
func FileExists(path string) (bool, error) {
var err *OSError
return false, err
}
func main() {
if _, err := FileExists("/no/such/file"); err != nil {
fmt.Printf("error: %s\n", err)
} else {
fmt.Println("OK")
}
}

Explanation

The if statement in line 19 says that err != nil, but err prints out as < nil >.

Furthermore, err in line 14 ...