The Error Interface

In Go, errors are treated as normal values rather than special exceptions. This is achieved through the built-in error interface.

The error Interface

The error interface is a simple, pre-defined interface in Go:

type error interface {
    Error() string
}

Any type that implements the Error() string method is considered an error.

Error Handling Convention

When a function can fail, it should return an error as its last return value. The caller must then check if that error is nil.

  • nil error: Indicates success.
  • Non-nil error: Indicates failure.
i, err := strconv.Atoi("42")
if err != nil {
    // Handle the error
    fmt.Println("Error:", err)
    return
}
// Success: Use i

Best Practices

When returning a non-nil error, it is conventional to return the “zero values” for all other return parameters.