Multiple return
- Go course
- Beginner
- Lesson 31/90
- 4 min
Learn Go's multiple return and named return features.
Multiple return values
Go functions can return several values. The most common use is the (result, error) pair:
func bolKalan(a, b int) (int, int) {
return a / b, a % b
}
bolum, kalan := bolKalan(17, 5)
fmt.Println(bolum, kalan) // 3 2If you don't need a value, skip it with _: _, kalan := bolKalan(17, 5).
Named return values
Return values can be named; the names are variables declared with zero values at the start of the function, and a bare return returns them:
func minMax(s []int) (min, max int) {
min, max = s[0], s[0]
for _, v := range s {
if v < min { min = v }
if v > max { max = v }
}
return
}It helps documentation in short functions; in long functions bare returns make reading harder.
Practice Minimum and maximum
Write minMax(s []int) (min, max int) with named returns. Print the result of minMax([]int{4, 9, 1, 7}).
Starter code
package main
import "fmt"
func main() {
// buraya yaz
}Sample solution
package main
import "fmt"
func minMax(s []int) (min, max int) {
min, max = s[0], s[0]
for _, v := range s {
if v < min {
min = v
}
if v > max {
max = v
}
}
return
}
func main() {
fmt.Println(minMax([]int{4, 9, 1, 7}))
}Expected output
1 9
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Why do you discard an unused return value with <code>_</code>?
- It runs faster
- The value is reset
- It isn't required, it doesn't matter
- Go gives a compile error for an unused local variable Correct answer
Explanation: A declared but unused variable is an error in Go; the blank identifier _ shows you are ignoring the value on purpose.
2 Skip a value
____, kalan := bolKalan(17, 5)
_, kalan := bolKalan(17, 5)
Explanation: The blank identifier _ discards an unwanted return value.
3 Syntax
| Term | Meaning |
|---|---|
(int, int) |
Two return types |
(min, max int) |
Named returns |
return |
Bare return |
_ |
Ignore the value |