Notes on Go, part 3 of ∞

Here are my notes on how multiple returns work.

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

func main() {
    results := split(17)
    fmt.Println(results)
    fmt.Println(split(17))
}

Returns prog.go:12: multiple-value split() in single-value context (Check it out on the Go Playground)

package main

import "fmt"

func split(sum int) (x, y int) {
    x = sum * 4 / 9
    y = sum - x
    return
}

func main() {
    resultsx, resultsy := split(17)
    fmt.Println(resultsx)
    fmt.Println(resultsy)
    fmt.Println(split(17))
}

Returns:

7
10
7 10

(Check it out on the Go Playground)

If a function returns multiple things, you are required to give each of those things a name if you are going to save them to a variable. The exception (so far) is if you directly pass the function to another function that can handle that sort of thing.

If you don’t want to save one of the returns, you can assign it to _, which basically says ‘I know there is going to be something here, throw it out immediately’.