How to return errors as values and not just pointers in Go?

In Go, errors are usually returned as values, not pointers. You can create and return an error using the errors.New() function, or use the fmt.Errorf() function for more complex error messages.

Here's an example of returning an error as a value:

package main import ( "errors" "fmt" ) func divide(a, b int) (int, error) { if b == 0 { return 0, errors.New("division by zero") } return a / b, nil } func main() { result, err := divide(6, 0) if err != nil { fmt.Println("Error:", err) return } fmt.Println("Result:", result) }

In the divide() function, we check if the divisor (b) is zero and return an error using errors.New() if it is. Otherwise, we return the result and nil for the error.

In the main() function, we call divide(6, 0) and check if the returned error is nil before printing the result. If an error occurred, we handle it accordingly.

This approach allows you to return meaningful error messages along with the values, without the need for pointers.