How to return an error from a function in Go?

In Go, returning an error from a function is a common and idiomatic way of handling errors. Here's how you can return an error from a function in Go:

  1. Define an error type:
type MyError struct { Message string }
  1. Implement the error interface for the error type:
func (e *MyError) Error() string { return e.Message }
  1. Use the error type in your function and return an instance of it when an error occurs:
func doSomething() error { // If an error occurs, return an instance of the error type if condition { return &MyError{ Message: "Something went wrong", } } // No error, return nil return nil }
  1. In the calling code, check if an error was returned and handle it accordingly:
err := doSomething() if err != nil { // Handle the error fmt.Println(err) }

This way, your function doSomething can indicate that an error occurred by returning a non-nil error value of the appropriate type, and the calling code can react accordingly.