We begin with the error data type because errors play a key role in Go.

Go provides a special data type for representing error conditions and error messages named error—in practice, this means that Go treats errors as values. In order to program successfully in Go, we should be aware of the error conditions that might occur with the functions and methods we are using and handle them accordingly.

The next convention for error messages

As we already know, Go follows the next convention about error values: if the value of an error variable is nil, then there was no error.

Example

As an example, let’s consider strconv.Atoi(), which is used for converting a string value into an int value (Atoi stands for ASCII to Int). As specified by its signature, strconv.Atoi() returns (int, error). Having an error value of nil means that the conversion was successful and that we can use the int value if we want. Having an error value that is not nil means that the conversion was unsuccessful and that the string input is not a valid int value.

Get hands-on with 1200+ tech skills courses.