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.
-
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, return0, total.
-
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 + serijumlahMain= number of matches played (menang + seri + kalah)hasilLiga(4, 2, 1)→14, 7