Functions and Multiple Return Values
Declaring functions, and Go's distinctive support for returning more than one value.
What you'll learn
- Declare a function with typed parameters and a return type
- Return and receive multiple values from a single function call
- Explain why Go's error-handling idiom depends on multiple return values
Explanation
A Go function declares its parameter types and return type explicitly: func add(a int, b int) int { return a + b }. Consecutive parameters sharing a type can drop the repeated type name: func add(a, b int) int.
Go functions can return more than one value -- a feature many other mainstream languages don't have built in. This is written as func divide(a, b int) (int, int) { return a / b, a % b }, and callers receive both values: quotient, remainder := divide(17, 5).
This isn't just a convenience -- it's the foundation of Go's core error-handling idiom, which you'll see properly in a later lesson: a function that might fail returns its normal result and an error value, e.g. func parse(s string) (int, error), and the caller checks the error before trusting the result.
If you don't need one of the returned values, you can discard it with the blank identifier _, e.g. quotient, _ := divide(17, 5) if you only care about the quotient.
Guided lab
Predict: A function with two return values
Read this program and predict exactly what it prints.
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q, r := divide(17, 5)
fmt.Printf("17 / 5 = %d remainder %d\n", q, r)
}Stuck? Get a hint.
Common mistakes
- Forgetting to receive all values a multi-return function produces -- Go requires you to either use or explicitly discard (`_`) every returned value at the call site.
- Mismatching the number of variables on the left of `:=` with the number of values a function actually returns.
- Assuming multiple return values are a special struct or tuple type -- they aren't; they're just multiple plain values in the function signature.
Knowledge check
Takeaway
Go functions can return multiple values directly, which is the foundation of its `(result, error)` error-handling idiom.
Summary
Functions declare typed parameters and return types; Go's multi-value returns let a function hand back more than one result, discardable with `_`.
References
Your notes
Notes save automatically.
Finished this lesson?
Mark it complete to track your progress and schedule a future review.
AI tutor
The optional AI tutor isn't enabled in this deployment. All lessons, exercises, quizzes, and search work fully without it.