ProgramGuru

Function Return Values

Start with Function Return Values

A function can compute a result and return it to its caller. Returning is different from printing: the caller gets a value it can store or use in another calculation.

What you’ll learn

  • Explain the main purpose of function return values.
  • Read and run the complete Go example in this lesson.
  • Apply the concept and recognize common mistakes.

Understand the idea

Place the return type after the parameter list: func square(n int) int. Inside the function, return n * n ends the call and supplies an int result. A function with a declared result type must return an appropriate value on every reachable path that requires one.

Prefer returning calculated values from reusable functions rather than printing inside every function. The calling code can then decide whether to print, save or further transform the result.

Visualize how it works

Follow this diagram before executing the example. Check where a value or decision changes what runs next.

Visual explanation for returnA returned value can be reused by the caller.Call square(6)Step 1Compute 6 × 6Step 2Return 36Step 3Store in resultStep 4A returned value can be reused by the caller.
A returned value can be reused by the caller.

Run a complete Go example

This example is a complete program. Save it as main.go or paste it into the Go Playground.

Go code

package main

import "fmt"

func square(n int) int {
	return n * n
}
func main() {
	result := square(6)
	fmt.Println("Square:", result)
	fmt.Println("Plus one:", square(4)+1)
}

Output

Square: 36
Plus one: 17

Trace what the program does

The first call evaluates 6 * 6 and returns 36, which is assigned to result. The second call returns 16; main adds one and prints 17. Neither return statement prints by itself.

Avoid common mistakes

  • return sends a value back; fmt.Println displays text and has a different purpose.
  • Code after an unconditional return in the same block is unreachable.

Try it yourself

Write a cube(n int) int function and print the cube of 3 without putting a print inside cube.

Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.

Check your understanding

What does return n*n do?
Choose one answer. You can try again.

Answer and explanation

Supplies a result to the caller and exits the function

Correct. The first call evaluates 6 * 6 and returns 36, which is assigned to result.

What you should remember

You have practiced Function Return Values in a small, self-contained program. The important habit is to predict what runs, inspect the actual output and distinguish the language rule from the particular example.

Before continuing, make sure you can explain the program to someone who has not seen it, including the line that changes its result.

Reaching the recap and completing the quizzes are separate milestones.

    Next lesson: Multiple Return Values →