create a function that returns an error in go

In Go, functions can return an error as one of their return values. This is a common pattern used to indicate that something went wrong during the execution of the function. Here's an example of how to create a function that returns an error:

main.go
func divide(a, b float64) (float64, error) {
    if b == 0 {
        // return an error if b is zero
        return 0, fmt.Errorf("cannot divide by zero")
    }
    // divide a by b and return the result
    return a / b, nil
}
228 chars
9 lines

In the above code, the divide function takes two float64 parameters a and b and returns a float64 and an error. If b is zero, the function returns an error using fmt.Errorf function. Otherwise, it returns the result of dividing a by b.

To use this function, you can do something like this:

main.go
result, err := divide(10, 0)
if err != nil {
    // handle error
    panic(err)
}
fmt.Println(result)
102 chars
7 lines

In the above code, we call the divide function with a=10 and b=0. Since b is zero, the function returns an error. We check if the error is nil, indicating that there was no error. If the error is not nil, we panic with the error message. If there was no error, we print the result using fmt.Println function.

related categories

gistlibby LogSnag