Go Multiple Return Values 🎯

beginner
16 min

Go Multiple Return Values 🎯

Welcome to our deep dive into Go's Multiple Return Values! In this lesson, we'll explore how to return more than one value from a Go function, making your code more flexible and powerful. Let's get started!

Introduction 📝

In Go, a function can return multiple values to the caller. This feature allows us to package related pieces of information and return them as a single unit, making our code more expressive and easier to work with.

Basic Concepts 💡

A Go function can return multiple values by separating them with commas in the function signature and by using multiple return statements in the function body.

go
func exampleFunc(x, y int) (int, int) { sum := x + y difference := x - y return sum, difference }

In this example, exampleFunc takes two integer arguments, x and y, and returns two integer values, sum and difference.

Multiple Return Values in Practice 💡

Let's take a look at a practical example. Imagine we're writing a function to calculate the area and perimeter of a rectangle.

go
func rectangle(width, height int) (int, int) { area := width * height perimeter := 2 * (width + height) return area, perimeter }

Here, we define a function rectangle that calculates the area and perimeter of a rectangle given its width and height. We then return both the area and perimeter as separate integer values.

Receiving Multiple Return Values 💡

To receive multiple return values from a Go function, we use multiple variables to capture the returned values in the order they are returned.

go
area, perimeter := rectangle(5, 10) fmt.Println("Area:", area) fmt.Println("Perimeter:", perimeter)

In this example, we call the rectangle function and assign the returned values to area and perimeter variables. We then print the calculated values.

Quiz 🎯

Quick Quiz
Question 1 of 1

Which function in the example calculates the area and perimeter of a rectangle?

Error Handling with Multiple Returns 💡

Go's multiple returns also provide a way to handle errors by returning both a value and an error indicator.

go
func divide(dividend, divisor int) (quotient int, err error) { if divisor == 0 { err = errors.New("division by zero") return } quotient = dividend / divisor return }

In this example, we define a function divide that calculates the quotient of two integers. If the divisor is zero, we return an error along with the function.

Conclusion 🎯

Go's multiple return values provide a powerful and flexible way to package and return information from functions. They can make your code more expressive, easier to work with, and better suited for real-world applications. Happy coding! 🚀