14. Error
It is idiomatic in Go to use the error interface type as the return type for any error that is going to be returned from a function or method. This interface is used by all the functions and methods in the standard library that return errors.
Go code uses error values to indicate an abnormal state. For example, the os.Open function returns a non-nil error value when it fails to open a file.
func Open(name string) (file *File, err error)
The following code uses os.Open to open a file. If an error occurs it calls log.Fatal to print the error message and stop.
1 f, err := os.Open("filename.ext")
2 if err != nil {
3 log.Fatal(err)
4 }
5 // do something with the open *File f
Handling errors that are returned from functions and methods starts by checking if the returned interface value of type error is not nil. Thus in the above code, the value of the err variable is compared to the value of nil. If the value is not nil, then there was an error.
In Go, error handling is important. The language’s design and conventions encourage you to explicitly check for errors where they occur (as distinct from the convention in other languages of throwing exceptions and sometimes catching them). In some cases this makes Go code verbose.