The error interface is a fundamental concept in Go programming, playing a crucial role in error handling and management. It provides a standardized way to represent and work with errors across the language and its standard library.
In Go, the error interface is defined as:
type error interface {
Error() string
}
This simple interface requires any type that implements it to have an Error()
method that returns a string. This method typically provides a description of the error.
The error interface is commonly used as a return type for functions that can fail. Here's a basic example:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
In this example, the function returns an error when division by zero is attempted. Otherwise, it returns nil
for the error.
When calling a function that returns an error, it's idiomatic in Go to check the error immediately:
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
return
}
fmt.Println("Result:", result)
You can create custom error types by implementing the error interface. This allows for more detailed error information:
type MyError struct {
Code int
Message string
}
func (e *MyError) Error() string {
return fmt.Sprintf("error %d: %s", e.Code, e.Message)
}
func someFunction() error {
return &MyError{Code: 404, Message: "Not Found"}
}
The error interface is a cornerstone of Go's approach to error handling. By providing a simple, consistent way to work with errors, it enables robust and reliable code. Understanding and effectively using the error interface is essential for writing idiomatic and reliable Go programs.
For more advanced error handling techniques, explore creating custom errors and error handling best practices in Go.