Go Functions and Multiple Return Values
Return more than one value from a function.
Go
package main
import "fmt"
func divide(a, b int) (int, int) {
return a / b, a % b
}
func main() {
q, r := divide(17, 5)
fmt.Println(q, r)
}Output
3 2
Explanation
A Go function declares its parameter types after the names, and the form a, b int shares one type between both. A function can return several values, listed in parentheses, which Go programs use for results plus an error or, as here, a quotient plus a remainder.
The short declaration q, r := divide(17, 5) receives both results. Integer division truncates toward zero, so 17 / 5 is 3 and 17 % 5 is 2.
Explore the dry run
Guided walkthroughReady
1
package main2
3
import "fmt"4
5
func divide(a, b int) (int, int) {6
return a / b, a % b7
}8
9
func main() {10
q, r := divide(17, 5)11
fmt.Println(q, r)12
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Two int parameters in, two int results out. | — | — | |
| The call returns 3 and 2, assigned to q and r. | q = 3, r = 2 | — | |
| Println separates its arguments with a space. | q = 3, r = 2 | 3 2 |
Cost and common mistakes
O(1) time and space.
- Dividing an int by zero panics at runtime.
- Every declared variable must be used, otherwise the compiler reports an error. Use _ to discard a result you do not need.
Try it yourself
Predict divide(20, 6).
Reveal answer and reasoning
It returns 3 and 2, so the output is 3 2.