Multiple Return Values
Start with Multiple Return Values
A Go function can return more than one value. This is especially useful for returning a result together with information about whether an operation succeeded.
What you’ll learn
- Explain the main purpose of multiple return values.
- Read and run the complete Go example in this lesson.
- Apply the concept and recognize common mistakes.
Understand the idea
Write result types in parentheses, as in func divide(a, b int) (int, bool). The caller can receive both values using result, ok := divide(10, 2). Each result position has a type, and each return statement must supply matching values.
Multiple results are a core Go idiom: many standard-library functions return (value, error). We use bool here to keep the first example focused on the syntax, before studying the error interface.
Visualize how it works
Follow this diagram before executing the example. Check where a value or decision changes what runs next.
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 divide(a, b int) (int, bool) {
if b == 0 {
return 0, false
}
return a / b, true
}
func main() {
quotient, ok := divide(20, 4)
fmt.Println("First:", quotient, ok)
_, valid := divide(8, 0)
fmt.Println("Second valid:", valid)
}
Output
First: 5 true
Second valid: falseTrace what the program does
For 20 and 4, division produces 5 and the flag true. In the second call, b is zero, so the function returns 0 and false without dividing. The caller discards the unused quotient with _.
Avoid common mistakes
- Check the success or error result instead of assuming the first value is always valid.
- Use the blank identifier
_for a result that is intentionally ignored, not for data you still need.
Try it yourself
Change the function to return a quotient and remainder for nonzero divisors.
Tip: Edit the example above, predict the output, and run the modified code to test your reasoning.
Check your understanding
What you should remember
You have practiced Multiple 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.