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
func subtotal(price int, portions int) int: the wordfunc, the function's name, then the parameters in brackets (name first, then type), then the type of the return value, the result it gives back.return price * portionssends the result back to the caller and leaves the function at once.subtotal(15, 3)calls the function.15and3are the arguments: the values that go intopriceandportions, in order. The result,45, is stored indue.printReceipthas no return type. It just does something (prints), so there is no value toreturn.- Parameters of the same type can be shortened:
func subtotal(price, portions int) int. That's the form you use in the exercise:func add(a, b int) int,subtractandmultiply.subtract(10, 5)returns5,subtract(4, 9)returns-5,multiply(7, 6)returns42.
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
&meatballsis the address ofmeatballsin memory. A value that holds an address is called a pointer.*Menuis the type "pointer to Menu".m.Price = 18through a pointer changes the realmeatballs.- The argument's type must match the parameter.
raise(meatballs)into a*Menuparameter is refused:cannot use meatballs (variable of struct type Menu) as *Menu value in argument to raise.
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
- Inside the function,
pricesis a slice[]int. Three arguments become[15 12 5], no arguments become an empty slice. - Already have a slice? Put
...after it:total(orders...). Without the three dots,total(orders)is refused:cannot use orders (variable of type []int) as int value in argument to total.
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
func() intis a type: "a function with no parameters that returns an int".fmt.Printf("%T", next)prints exactly that.- Each call to
counter()makes a newnumber.nextandothereach have their ownnumber, and its value lasts between calls.
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
- Forgetting
return. A function of typeintthat only prints its result fails to compile withmissing return. - Too few arguments, or the wrong type.
subtotal(15)is refused withnot enough arguments in call to subtotal, andsubtotal("15", 3)withcannot use "15" (untyped string constant) as int value in argument to subtotal. - Expecting a function to change the original. Structs and numbers are copied. Use a pointer (
*Menuand&meatballs) when you do want to change the original. - A slice's items change after all. Go copies the slice, but the copy points at the same items.
prices[0] = 0inside a function turnsordersinto[0 12 5].
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.