0
0
GoConceptBeginner · 3 min read

What is error interface in Go: Simple Explanation and Example

In Go, the 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.

go
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")
	}
}
Output
Error: number is negative
🎯

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 error interface has one method: Error() string.
  • Functions return error to signal failure.
  • Check if the error is nil to 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.

Key Takeaways

The error interface in Go defines a simple way to represent errors with the Error() string method.
Functions return an error value to indicate if something went wrong, or nil if all is fine.
Checking for nil error values is the standard way to handle errors in Go programs.
Custom error types can be created by implementing the Error() method for more detailed error info.
Using the error interface keeps error handling clear, explicit, and consistent across Go code.