Go course

FunctionsMultiple Return Values

Go

Display

Theme

Functions · Test exercise

Multiple Return Values

A Go function can return more than one value. You list the return types in parentheses:

func bagi(a, b int) (int, int) {
	return a / b, a % b
}

hasil, sisa := bagi(17, 5)
fmt.Println(hasil, sisa) // 3 2

This feature shows up everywhere in Go, especially for returning a result and an error together (covered in the Errors chapter).

Ignoring values with _

Go doesn't allow unused variables. If you only need some of the values, use the blank identifier _:

_, sisa := bagi(17, 5) // nilai pertama dibuang
fmt.Println(sisa)

Here the first value is thrown away.

Named return values

You can also give return values names. Those variables are created automatically with their zero value at the start of the function, and a return with no arguments (a naked return) returns their latest values:

func statistik(benar, salah int) (total int, persenBenar int) {
	total = benar + salah
	persenBenar = benar * 100 / total
	return
}

Named return values work as documentation: the reader can tell right away what each value means. That said, a naked return is best kept for short functions — in a long function, writing return total, persenBenar explicitly is easier to read.

Task

Complete the following two functions.

  1. bagiTagihan(total, jumlahOrang int) (int, int) — a group of friends eats together at a food stall and splits the bill evenly. Return each person's share (integer division) and the remainder that's left unsplit.

    • bagiTagihan(100000, 3) → 33333, 1
    • If jumlahOrang <= 0, return 0, total.
  2. hasilLiga(menang, seri, kalah int) (poin int, jumlahMain int) — a futsal league table, from wins, draws, and losses. Use a named return:

    • poin (points) = 3 * menang + seri
    • jumlahMain = number of matches played (menang + seri + kalah)
    • hasilLiga(4, 2, 1) → 14, 7
main.go
package main

import "fmt"

func bagiTagihan(total, jumlahOrang int) (int, int) {
	// TODO: kembalikan bagian tiap orang dan sisanya
	return 0, 0
}

func hasilLiga(menang, seri, kalah int) (poin int, jumlahMain int) {
	// TODO: isi poin dan jumlahMain, lalu return
	return
}

func main() {
	bagian, sisa := bagiTagihan(100000, 3)
	fmt.Println("Bagian per orang:", bagian, "sisa:", sisa)

	poin, _ := hasilLiga(4, 2, 1)
	fmt.Println("Poin:", poin)
}

Output

Go runtime not loaded yet

Press Run to see the output, or Submit to check your code.

Ctrl/Cmd + Enter: Run · Ctrl/Cmd + Shift + Enter: Submit · Ctrl/Cmd + S: tidy the code (gofmt)