In Go, a function can have multiple return values. This feature allows a function to return more than one value, which can be useful in various scenarios. Here’s an example that demonstrates multiple return values:
package main
import "fmt"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero error")
}
return a / b, nil
}
func main() {
result, err := divide(10, 2)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
}
In this example, the divide
function takes two floating-point numbers as input and returns the division result and an error (if any). If the second argument is zero, it returns an error to indicate a division by zero. Otherwise, it calculates and returns the division result.
In the main
function, we call the divide
function with arguments 10 and 2. We use the multiple assignment syntax to capture both the division result and the error returned by the function. If the error is nil
, we print the result; otherwise, we print the error message.
The output of this program will be:
Result: 5
Here, the divide
function demonstrates the use of multiple return values to return the division result and an error. This pattern is commonly used in Go to return additional information alongside the main result, such as error states, boolean flags, or additional computed values.
It’s important to note that the order of the returned values must match the order of the function’s return type declaration. The caller of the function must also handle all the returned values appropriately to avoid potential errors or unexpected behavior.
Multiple return values in Go provide a clean and efficient way to handle complex return scenarios and can make code more readable and expressive.