Day 9: Go Functions with Multiple Return Values - A Practical Guide
Go allows functions to return multiple values, which is particularly useful for error handling. Today, we’ll write functions that return both results and errors.
Step 1: Defining Functions with Multiple Returns
In Go, functions can return more than one value. Here’s an example of a function that returns two integers:
func swap(a, b int) (int, int) {
return b, a
}
Step 2: Error Handling with Multiple Returns
Go uses multiple return values for error handling. Instead of throwing exceptions, Go functions return an error as the second return value:
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("division by zero")
}
return a / b, nil
}
To handle the error, you check if the error is nil
:
result, err := divide(10, 0)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Result:", result)
}
Practical Exercise
Write a function that calculates the square root of a number. Return both the result and an error if the input is negative:
package main
import (
"errors"
"fmt"
"math"
)
func sqrt(x float64) (float64, error) {
if x < 0 {
return 0, errors.New("cannot compute square root of a negative number")
}
return math.Sqrt(x), nil
}
func main() {
result, err := sqrt(-9)
if err != nil {
fmt.Println("Error:", err)
} else {
fmt.Println("Square root:", result)
}
}