DMarlon Studio

Lesson 12 · 12 of 20

Functions and multiple results · Go

Write Go functions with parameters and a result type, return several values at once and use named results.

Go · Functions and multiple results in DMarlon Studio: the example's code and its output in the terminal

A function is declared with func, its name, its parameters with their types and, at the end, the type of what it returns: func vat(price float64) float64. return hands back the result: vat(40) gives 8.40 of VAT. When the body is short, it can sit on a single line.

In Go a function can return several values. share returns two ints, what each child gets and what is left over: return sweets / children, sweets % children. When two parameters in a row share a type, you only write it once: sweets, children int.

The caller picks up both results at once: each, left := share(17, 5) gives 3 and 2. You take all of them or none, so if you only need one, throw the other away with _, as in _, rest := share(100, 7).

Named results, like (low, high int), are variables that start at their zero value; the function fills them in and a bare return sends them back. lowHigh takes a slice, starts from the first number and walks the rest, keeping the lowest and the highest: 9 and 31.

Code · main.go

package mainimport "fmt"// Parameters go with their types; the result type comes last.func vat(price float64) float64 { return price * 0.21 }// A function can return several values.func share(sweets, children int) (int, int) {	return sweets / children, sweets % children}// Named results start at zero; a bare return sends them back.func lowHigh(numbers []int) (low, high int) {	low, high = numbers[0], numbers[0]	for i := 1; i < len(numbers); i++ {		if numbers[i] < low {			low = numbers[i]		} else if numbers[i] > high {			high = numbers[i]		}	}	return}func main() {	fmt.Printf("VAT on 40 euros: %.2f\n", vat(40))	each, left := share(17, 5)	fmt.Println("Sweets each:", each, "left over:", left)	_, rest := share(100, 7) // _ ignores a result	fmt.Println("Left over from 100 among 7:", rest)	low, high := lowHigh([]int{18, 25, 9, 31, 22})	fmt.Println("Lowest:", low, "highest:", high)}

Output · go run main.go

VAT on 40 euros: 8.40
Sweets each: 3 left over: 2
Left over from 100 among 7: 2
Lowest: 9 highest: 31

Key points

  • func name(p type) result { } declares a function.
  • a, b int shares the type between parameters in a row.
  • A function can return several values: return x, y.
  • _ throws away a result you do not need.
  • With named results, a bare return sends them back.

Exercise

Write func average(numbers []int) (float64, int), which returns the average and how many numbers there are, and use it with the same marks as lowHigh.