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 one of the returned values, you can use the blank identifier _ to ignore the other. For example, to get only the quotient:

q, _ := divide(7, 3)
fmt.Println("Quotient:", q)

The _ discards the remainder so the compiler does not complain about an unused variable.

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.

Cheat sheet

Go functions can return multiple values at once. Specify multiple return types in parentheses and return multiple values separated by commas:

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

Capture multiple return values using multiple variables in the assignment:

q, r := divide(7, 3)

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