Menu
Coddy logo textTech

Named Return Values

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

In Go, you can name your return values in function declarations. This makes your code more readable and allows you to return by just using a plain return statement.

Create a function with named return values:

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

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

The output is the same as before:

7 ÷ 3 = 2 with remainder 1

Named return values are initialized to their zero values and can be assigned directly in the function body.

challenge icon

Challenge

Beginner

In this challenge, you'll practice using named return values in Go functions.

Complete the function getPersonInfo that returns a person's name, age, and whether they are a student. The function already has named return parameters, but you need to assign values to them.

The function should return the predefined values for a person named 'Alex' who is 25 years old and is a student.

Cheat sheet

In Go, you can name your return values in function declarations for better readability and use a plain return statement:

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

Named return values are initialized to their zero values and can be assigned directly in the function body.

Try it yourself

package main

import "fmt"

// This function uses named return values
func getPersonInfo() (name string, age int, isStudent bool) {
	// TODO: Assign values to the named return variables
	// name should be "Alex"
	// age should be 25
	// isStudent should be true
	
	// The "return" statement without arguments will return the named return values
	return
}

func main() {
	name, age, isStudent := getPersonInfo()
	fmt.Printf("Name: %s\nAge: %d\nStudent: %t\n", name, age, isStudent)
}
quiz iconTest yourself

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

All lessons in Fundamentals