Functions in Go

A function is written func name(parameter type) resultType { return ... }, and parameters of the same type can be shortened: func add(a, b int) int. Arguments…

The cashier at Bimo's Meatball Stall hands the kitchen a slip, "Tendon Meatballs, $15, 3 portions". The kitchen works it out and cooks, then sends back one tray. The cashier doesn't need to know how it is cooked. It is enough to know which slip went in and which tray comes back.

In a program, that kitchen is a function: a named piece of code that takes values in and can give a result back. The slip is the argument, the tray is the return value. One more thing that matters: the kitchen only ever gets a photocopy of the slip. Scribble on it in the kitchen and the original at the till stays clean.

The shape of a function

package main

import "fmt"

func subtotal(price int, portions int) int {
	return price * portions
}

func printReceipt(name string, amount int) {
	fmt.Println(name, amount)
}

func main() {
	due := subtotal(15, 3)
	printReceipt("Tendon Meatballs", due)
	fmt.Println(subtotal(12, 2))
}
$ go run stall.go
Tendon Meatballs 45
24

Arguments are always copied

Go always gives a function a copy of its arguments. A Menu struct is copied whole:

type Menu struct {
	Name  string
	Price int
}

func raise(m Menu) {
	m.Price = 18
	fmt.Println("in raise:", m.Price)
}

func main() {
	meatballs := Menu{Name: "Tendon Meatballs", Price: 15}
	raise(meatballs)
	fmt.Println("in main:", meatballs.Price)
}
in raise: 18
in main: 15

m is a photocopy of meatballs. Only the photocopy changes, and it is thrown away as soon as raise ends. So main still prints 15.

For a function to change the original, send its address:

func raise(m *Menu) {
	m.Price = 18
}

raise(&meatballs) // now in main: 18

Variadic: any number of arguments

... before the type of the last parameter means "any number of these":

func total(prices ...int) int {
	sum := 0
	for _, p := range prices {
		sum += p
	}
	return sum
}

orders := []int{15, 12, 5}
fmt.Println(total(15, 12, 5)) // 32
fmt.Println(total(orders...)) // 32
fmt.Println(total())          // 0

Functions are values too: closures

A function can be stored in a variable and returned from another function. A function that uses a variable from outside itself is called a closure, and it takes that variable wherever it goes:

func counter() func() int {
	number := 0
	return func() int {
		number++
		return number
	}
}

next := counter()
fmt.Println("next:", next())   // next: 1
fmt.Println("next:", next())   // next: 2
other := counter()
fmt.Println("other:", other()) // other: 1

Named results

A function's results can be given names in the signature. The variables exist from the start of the function, holding their zero value, and a return with nothing after it (a bare return) gives them back:

func subtotal(price, portions int) (result int) {
	if portions <= 0 {
		return // result is still 0
	}
	result = price * portions
	return
}

fmt.Println(subtotal(15, 0), subtotal(15, 3)) // 0 45

In a short function, writing return result out is easier to read.

⚠️ A forgotten return and arguments that turn out to be copies

TL;DR: A function is written func name(parameter type) resultType { return ... }, and parameters of the same type can be shortened: func add(a, b int) int. Arguments go in by position and are always copied, so raise(m Menu) does not change meatballs; send &meatballs to a *Menu parameter to change the original. ...int takes any number of arguments as a slice, and a slice is passed with total(orders...). Functions are values: a closure carries its own variable, so next() returns 1, 2, 3. Results can be named, and then an empty return (a bare return) gives them back. Forgetting return means missing return.

⚡ A slip goes in, a tray comes out

Write:

func subtotal(price int, portions int) int {
	return price * portions
}

due := subtotal(15, 3) // 45

Meaning: price and portions are parameters, 15 and 3 are the arguments, filled in by position. return sends the result back to the caller. Parameters of the same type can be shortened: func add(a, b int) int.

⚡ Arguments are always copied

Guess first: func raise(m Menu) sets m.Price = 18. After raise(meatballs), what is meatballs.Price in main?

Still 15. m is only a photocopy of meatballs, and the photocopy is thrown away as soon as raise ends.

Meaning: Want to change the original? Send its address, raise(&meatballs), to a *Menu parameter.

⚡ Named results

Write:

func subtotal(price, portions int) (result int) {
	result = price * portions
	return
}

Meaning: result exists from the start of the function with its zero value, and an empty return (a bare return) gives it back. In a short function, return result is easier to read.

What you will learn