What is error interface in Go: Simple Explanation and Example
error interface is a built-in type used to represent errors. It requires a single method Error() string that returns a descriptive error message, allowing functions to communicate failure in a simple, consistent way.How It Works
The error interface in Go is like a contract that any error type must follow. It only needs one method: Error(), which returns a string describing what went wrong. Think of it as a simple way to pass around error messages without worrying about the details of the error's origin.
When a function encounters a problem, it can return an error value. The caller can then check if the error is nil (meaning no error) or not, and handle it accordingly. This keeps error handling clear and consistent across Go programs.
Because error is an interface, you can create your own error types with extra information, but as long as they implement the Error() method, they fit into Go’s error system seamlessly.
Example
This example shows a function that returns an error when a number is negative. The main function checks the error and prints the message.
package main import ( "errors" "fmt" ) func checkPositive(number int) error { if number < 0 { return errors.New("number is negative") } return nil } func main() { num := -5 err := checkPositive(num) if err != nil { fmt.Println("Error:", err.Error()) } else { fmt.Println("Number is positive") } }
When to Use
Use the error interface whenever a function might fail and you want to inform the caller about the problem. It is the standard way in Go to handle errors instead of exceptions.
Common real-world uses include:
- File operations (e.g., opening or reading files)
- Network requests (e.g., connection failures)
- Input validation (e.g., invalid user input)
- Custom error types for more detailed error handling
This approach helps keep your code clean and makes error handling explicit and easy to follow.
Key Points
- The
errorinterface has one method:Error() string. - Functions return
errorto signal failure. - Check if the error is
nilto know if something went wrong. - You can create custom error types by implementing the
Error()method. - This pattern makes error handling simple and consistent in Go.