CodeBlanks Logo Icon CodeBlanks

Multiple return

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 2

If 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

main.go
package main

import "fmt"

func main() {
    // buraya yaz
}

Sample solution

main.go
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

Question
____, kalan := bolKalan(17, 5)
Answer
_, 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

All lessons in Beginner