Menu
Coddy logo textTech

Returning Multiple Values

Part of the Fundamentals section of Coddy's GO journey — lesson 56 of 109.

Go functions can return multiple values at once, which is extremely useful for returning both results and error information.

Create a function that returns both a quotient and remainder:

func divide(a, b int) (int, int) {
    quotient := a / b
    remainder := a % b
    return quotient, remainder
}

func main() {
    q, r := divide(7, 3)
    fmt.Println("7 ÷ 3 =", q, "with remainder", r)
}

When you run this program, it outputs:

7 ÷ 3 = 2 with remainder 1

The function returns two values separated by commas, and we capture both values using multiple variables in the assignment.

If you only need some of the returned values, you can use the blank identifier _ to ignore the ones you don't need:

q, _ := divide(7, 3)  // ignore the remainder
fmt.Println("Quotient:", q)

Using _ tells Go to discard that return value. This is required when you don't use a value, since Go does not allow unused variables.

challenge icon

Challenge

Beginner

In this challenge, you'll practice returning multiple values from a function in Go.

We have a function called getPersonInfo that should return a person's name, age, and whether they are a student. Your task is to complete the function by adding the appropriate return statement.

Try it yourself

package main

import "fmt"

// This function should return three values: name, age, and isStudent
func getPersonInfo() (string, int, bool) {
	// Variables are already defined for you
	name := "Alex"
	age := 25
	isStudent := true
	
	// TODO: Return all three values (name, age, isStudent)
	
}

func main() {
	// Call the function and store the returned values
	name, age, isStudent := getPersonInfo()
	
	// Print the values
	fmt.Printf("Name: %s\n", name)
	fmt.Printf("Age: %d\n", age)
	fmt.Printf("Is Student: %t\n", isStudent)
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Fundamentals