A Go function can return an error value alongside its result. By convention, the error comes last, making a potentially failing operation visible in the function signature. A nil error means the operation succeeded; a non-nil error needs a decision at the call site. section 2.6.2 section 7.1
Listing 7.3 The error interface
type error interface {
Error() string
}
The error type is an interface with one method, Error() string. A non-nil value reports that something happened; its message reports what. An error can also carry more information or behavior. section 7.2
Reading a file
os.ReadFile(filename) returns file contents and an error. Capture both, then check err immediately. For a small program, a non-nil error can be logged to standard error before os.Exit(1); continue using the contents only when the check passes. section 2.6.2 section 2.6.3
The same design works in an application interface: a key/value store might declare Put and Delete as returning error, and Get as returning (string, error). Callers can see which operations may fail and handle each result near the call rather than in a distant exception handler. section 7.1
After a non-nil check, choose a response that fits the failure:
- Return the error to the caller, with additional context if useful. section 7.2 section 7.4
- Retry, or log and exit when the program cannot continue. section 7.2
- Ignore it only deliberately; discarding an error is normally an antipattern. section 7.4
