Return multiple results
Return multiple results
A Go function may return more than one result. Write the result types in parentheses, then return one value for each result in the declared order. At the call site use multiple assignment to receive them.
package main
import "fmt"
func divmod(n, d int) (int, int) { return n / d, n % d }func main() { q, r := divmod(17, 5) fmt.Println(q, r)}17 divided by 5 has integer quotient 3 and remainder 2. This example requires a nonzero divisor. The returned values are separate results, not an array or tuple object.
Report whether an operation succeeded
package main
import "fmt"
func divide(n, d int) (int, bool) { if d == 0 { return 0, false } return n / d, true}func main() { value, ok := divide(12, 3) fmt.Println(value, ok) _, ok = divide(12, 0) fmt.Println(ok)}Check ok before using the result. _ discards a result intentionally; it is not storage. A call returning two values cannot be assigned to one variable. Go commonly returns a value with an error; errors are covered in a later chapter.
Try it locally
Write bounds(a,b int) (int,int) returning the smaller then larger number. Print bounds(8,3) and bounds(4,4).
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Functions 03: Return multiple results
Check the lesson objective before moving on.
How many variables are needed to receive both results from divmod?
What does the blank identifier _ do in assignment?