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.go228 chars9 linesIn 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.go102 chars7 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.
gistlibby LogSnag