These are the notes for Go episode 9. Your programs can decide and repeat, but everything still lives in one long main. Today you'll package a piece of work, give it a name, and use it anywhere: a function. You will learn function declarations, parameters and arguments, results and return, the function signature, multiple return values, named results and the naked return, variadic functions (and passing a slice with ...), pass by value, and functions as values: function types and higher-order functions. Every example runs as-is in the SyntaxPilot compiler (language: Go); outputs and errors are from real runs (Go 1.24).
The problem: one tax rule, copied into three shops
Three shops use our billing program, and every bill adds 18% tax: price + price*18/100. So we copy that rule into three places:
package main
import "fmt"
func main() {
chai := 50
fmt.Println("chai stall:", chai+chai*18/100)
cake := 400
fmt.Println("bakery:", cake+cake*18/10)
pens := 200
fmt.Println("stationery:", pens+pens*18/100)
}
chai stall: 59
bakery: 1120
stationery: 236
59 and 236 are right, but the bakery says 1120 for a Rs 400 cake. One copy says 18/10 instead of 18/100. Now imagine fifty shops, or the tax rate changing: you'd have to find and edit fifty copies without missing one. Copy-pasted logic is a bug waiting to happen. We want to write the rule once, give it a name, and use the name everywhere.
Your first function
Think of a sugarcane juice machine: built once, used all day.
| At the juice stall | In Go | Name |
|---|---|---|
| The machine | func withGST(...) int { ... } |
a function |
| The slot that accepts sugarcane | price int |
a parameter |
| The stick you feed in today | withGST(400) |
an argument |
| The glass of juice that comes out | return price + ... |
the result (return value) |
package main
import "fmt"
func withGST(price int) int {
return price + price*18/100
}
func main() {
fmt.Println("chai stall:", withGST(50))
fmt.Println("bakery:", withGST(400))
fmt.Println("stationery:", withGST(200))
}
chai stall: 59
bakery: 472
stationery: 236
Reading the declaration func withGST(price int) int { ... }:
funcstarts a function declaration;withGSTis its name.(price int)is the parameter list: named inputs, each with a type. Inside the function,priceis an ordinary variable.- The
intafter the brackets is the result type: what the function gives back. returnends the function and sends a value back to the caller.- The first line (name, parameters, results) is the function's signature: its contract with the rest of the program.
withGST(400) is a call: it runs the function with the argument 400, and the whole call expression becomes the returned value, 472. There's now one place where the tax rule lives; change 18 to 12 there, and every shop updates. Functions are declared at package level (outside main), and main itself is just the function Go calls first.
More signature shapes:
| Signature | Meaning |
|---|---|
func greet() |
no parameters, no result |
func square(n int) int |
one int in, one int out |
func area(l, w int) int |
two ints in (shared type written once) |
func share(laddoos, kids int) (int, int) |
two ints in, two ints out |
func toHMS(total int) (h, m, s int) |
named results |
func total(prices ...int) int |
any number of ints in |
The signature is a contract
package main
import "fmt"
func withGST(price int) int {
return price + price*18/100
}
func main() {
fmt.Println(withGST(100, 5))
fmt.Println(withGST("100"))
}
# command-line-arguments
./main.go:10:30: too many arguments in call to withGST
have (number, number)
want (int)
./main.go:11:25: cannot use "100" (untyped string constant) as int value in argument to withGST
Go checks every call against the signature before the program runs: the number of arguments (have (number, number) / want (int)) and their types. (number is how Go describes an untyped numeric constant like 100.)
Printing is not returning
package main
import "fmt"
func withGST(price int) int {
fmt.Println(price + price*18/100)
}
func main() {
fmt.Println(withGST(100))
}
# command-line-arguments
./main.go:7:1: missing return
The signature promises an int, so every path through the function must end in return with an int. fmt.Println shows a value on the screen; return hands it back to the caller. They are different things.
A function with no result type needs no return (you can still write a bare return to leave early):
package main
import "fmt"
func greet(name string) {
if name == "" {
fmt.Println("Hello, stranger!")
return
}
fmt.Println("Hello,", name+"!")
}
func main() {
greet("Asha")
greet("")
}
Hello, Asha!
Hello, stranger!
Multiple return values
Sharing 10 laddoos among 3 kids gives two answers: 3 each, 1 left over. In Go, a function can return several values: list the result types in brackets and return the values separated by commas.
package main
import "fmt"
func share(laddoos, kids int) (int, int) {
return laddoos / kids, laddoos % kids
}
func main() {
each := share(10, 3)
fmt.Println(each)
}
# command-line-arguments
./main.go:10:13: assignment mismatch: 1 variable but share returns 2 values
laddoos, kids int is a shortcut: neighbouring parameters with the same type can share it. Catching two results in one variable fails: Go won't silently drop an answer. Take both, or ignore one with the blank identifier _:
package main
import "fmt"
func share(laddoos, kids int) (int, int) {
return laddoos / kids, laddoos % kids
}
func main() {
each, left := share(10, 3)
fmt.Println("each:", each, "left:", left)
_, extra := share(25, 4)
fmt.Println("extra:", extra)
}
each: 3 left: 1
extra: 1
This style is everywhere in Go: very soon you'll write functions that return a value and an error, like n, err := strconv.Atoi("42").
Named results and the naked return
Results can have names too:
package main
import "fmt"
func toHMS(total int) (h, m, s int) {
h = total / 3600
m = total % 3600 / 60
s = total % 60
return
}
func main() {
h, m, s := toHMS(9876)
fmt.Println(h, "h", m, "m", s, "s")
}
2 h 44 m 36 s
(h, m, s int)declares three named result parameters. They're ordinary variables inside the function and start at their zero value (0 for ints).- A
returnwith nothing after it is a naked return: it returns the named results' current values. - Names document what each result means (
h, m, sis clearer thanint, int, int). - But in a long function, a bare
returnmakes the reader scroll up to see what's returned. Use naked returns only in short functions. You can also name results and still writereturn h, m, sexplicitly.
Variadic functions
A cart total: one customer buys nothing, one buys one item, one buys three. How many parameters? Put ... before the type:
package main
import "fmt"
func total(prices ...int) int {
sum := 0
for _, p := range prices {
sum += p
}
return sum
}
func main() {
fmt.Println(total())
fmt.Println(total(50))
fmt.Println(total(120, 80, 45))
}
0
50
245
prices ...intmeans any number of ints, even zero. A function like this is variadic.- Inside,
pricesis a slice of ints ([]int), so werangeover it. With no arguments it's empty, and the total is 0. fmt.Printlnis variadic too: that's why it takes as many values as you like.- Only the last parameter can be variadic:
func pay(o offer, prices ...int)is fine,func f(xs ...int, name string)is not (can only use ... with final parameter in list).
Passing a slice to a variadic function
package main
import "fmt"
func total(prices ...int) int {
sum := 0
for _, p := range prices {
sum += p
}
return sum
}
func main() {
cart := []int{120, 80, 45}
fmt.Println(total(cart))
}
# command-line-arguments
./main.go:15:23: cannot use cart (variable of type []int) as int value in argument to total
total wants separate ints, not one list. Add ... after the slice to spread it out into separate arguments:
package main
import "fmt"
func total(prices ...int) int {
sum := 0
for _, p := range prices {
sum += p
}
return sum
}
func main() {
cart := []int{120, 80, 45}
fmt.Println(total(cart...))
}
245
Remember: ...int before a type collects arguments into a slice; cart... after a slice spreads it out.
Pass by value
package main
import "fmt"
func discount(price int) {
price = price - 50
fmt.Println("inside:", price)
}
func main() {
price := 500
discount(price)
fmt.Println("outside:", price)
}
inside: 450
outside: 500
Inside, 450. Outside, still 500: the discount vanished. When you hand your Aadhaar card to an office, you give them a photocopy; if they scribble on it, your original is untouched. Go does the same: when you call a function, each argument's value is copied into the parameter. discount changed its own copy. This is called pass by value, and in Go every argument is passed by value.
The fix for now: return the new value and assign it back.
package main
import "fmt"
func discount(price int) int {
return price - 50
}
func main() {
price := 500
price = discount(price)
fmt.Println("now:", price)
}
now: 450
Code that only reads its inputs and returns a result is easy to test and hard to break. Episode 11 shows the other way: passing a pointer (the address of the original), so the function can change it. (Some types, like slices and maps, contain a pointer inside them, so a function can change their contents even though the slice value itself is copied; episodes 13-15 explain that.)
Functions as values
A shop runs different offers: Monday, flat Rs 50 off; Friday, 10% off. We don't want to rewrite checkout for each offer; we want to hand checkout the offer itself.
package main
import "fmt"
type offer func(int) int
func flat50(p int) int { return p - 50 }
func tenPercent(p int) int { return p - p/10 }
func checkout(price int, o offer) int {
return o(price)
}
func main() {
fmt.Println(checkout(800, flat50))
fmt.Println(checkout(800, tenPercent))
best := tenPercent
fmt.Printf("%T\n", best)
}
750
720
func(int) int
- Every function has a function type, made of its parameter and result types.
flat50andtenPercentboth have typefunc(int) int, and%Tprints it. type offer func(int) intgives that type a name: a named function type. Any function with that shape can be used as anoffer.checkout(800, flat50)passes the function itself: its name without brackets.flat50(800)would call it and pass the number 750 instead.- A function stored in a variable (
best := tenPercent) is called like any function:best(800). - A function that takes another function as a parameter, or returns one, is a higher-order function.
checkoutis one. - The zero value of a function type is
nil; calling a nil function panics, so make sure the variable holds a function first.
A function can also return a function:
package main
import "fmt"
func pick(day string) func(int) int {
if day == "Friday" {
return func(p int) int { return p - p/10 }
}
return func(p int) int { return p }
}
func main() {
offer := pick("Friday")
fmt.Println(offer(800))
fmt.Println(pick("Monday")(800))
}
720
800
func(p int) int { ... } without a name is a function literal (an anonymous function). Episode 10 is all about them.
Mini project: a checkout
Small functions, each doing one job:
package main
import "fmt"
func tenPercent(p int) int { return p - p/10 }
func withGST(p int) int { return p + p*18/100 }
func pay(o func(int) int, prices ...int) int {
sum := 0
for _, p := range prices {
sum += p
}
return withGST(o(sum))
}
func main() {
fmt.Println("to pay:", pay(tenPercent, 300, 450, 250))
}
to pay: 1062
pay adds up the prices (1000), then withGST(o(sum)) reads from the inside out: apply the offer (900), then add the tax (900 + 162 = 1062). The variadic parameter prices comes last, as it must. func tenPercent(p int) int { return p - p/10 } on one line is fine for very short functions; gofmt keeps it.
Common mistakes (and the real error messages)
| You wrote | Real error | Fix |
|---|---|---|
withGST(100, 5) |
too many arguments in call to withGST + have (number, number) / want (int) |
match the signature |
withGST() |
not enough arguments in call to withGST + have () / want (int) |
pass every argument |
withGST("100") |
cannot use "100" (untyped string constant) as int value in argument to withGST |
pass an int |
| printing instead of returning | missing return |
return the value |
each := share(10, 3) |
assignment mismatch: 1 variable but share returns 2 values |
each, left := or each, _ := |
total(cart) with cart []int |
cannot use cart (variable of type []int) as int value in argument to total |
total(cart...) |
| changing a parameter, expecting the caller's variable to change | no error: the change is lost | return the new value (or a pointer, episode 11) |
checkout(800, flat50(800)) |
cannot use flat50(800) (value of type int) as offer value in argument to checkout |
pass flat50, without brackets |
Practice
- Write
area(l, w int) intand call it for three rooms. - Write
minMax(a, b, c int) (int, int)returning the smallest and largest. - Write a variadic
average(nums ...int) float64. What should it return for no numbers? - Write a
flat100offer and plug it into the checkout.
Solutions and hints
1.
package main
import "fmt"
func area(l, w int) int {
return l * w
}
func main() {
fmt.Println("bedroom:", area(12, 10))
fmt.Println("kitchen:", area(8, 6))
fmt.Println("hall:", area(15, 12))
}
bedroom: 120
kitchen: 48
hall: 180
- Start with
aas both, then compare:
package main
import "fmt"
func minMax(a, b, c int) (int, int) {
lo, hi := a, a
for _, x := range []int{b, c} {
if x < lo {
lo = x
}
if x > hi {
hi = x
}
}
return lo, hi
}
func main() {
lo, hi := minMax(42, 7, 19)
fmt.Println("min:", lo, "max:", hi)
}
min: 7 max: 42
- Guard against dividing by zero, and convert to
float64before dividing (episode 4):
package main
import "fmt"
func average(nums ...int) float64 {
if len(nums) == 0 {
return 0
}
sum := 0
for _, n := range nums {
sum += n
}
return float64(sum) / float64(len(nums))
}
func main() {
fmt.Println(average(70, 85, 90))
fmt.Println(average())
}
81.66666666666667
0
len(nums) is the number of values in the slice.
4.
package main
import "fmt"
func flat100(p int) int { return p - 100 }
func withGST(p int) int { return p + p*18/100 }
func total(prices ...int) int {
sum := 0
for _, p := range prices {
sum += p
}
return sum
}
func pay(o func(int) int, prices ...int) int {
return withGST(o(total(prices...)))
}
func main() {
fmt.Println("to pay:", pay(flat100, 300, 450, 250))
}
to pay: 1062
1000 − 100 = 900, plus 18% = 1062. Same as 10% off here, because 10% of 1000 is exactly 100.
Quick quiz
What does this print?
func double(n int) int {
n = n * 2
return n
}
func main() {
x := 5
double(x)
fmt.Println(x, double(x))
}
- A.
5 10 - B.
10 10 - C.
10 20 - D.
5 5
Answer
A. 5 10. double gets a copy of x, so the first call changes nothing, and its result is thrown away (Go allows ignoring a single return value of a plain call statement). x is still 5, and double(x) returns 10.
Interview questions
- What is the difference between a parameter and an argument?
- What is a function signature? What does Go check at a call?
- How do you return several values? How do you ignore one?
- What are named results and the naked return? When should you avoid naked returns?
- What is a variadic function? What type does the variadic parameter have inside? How do you pass a slice to it?
- Is Go pass by value or pass by reference? What happens when a function changes its parameter?
- What is a function type? What is a higher-order function? Give an example.
- What's the difference between passing
fandf()to another function?
Glossary
| Term | Meaning | Example |
|---|---|---|
| Function | a named block of code you write once and call anywhere | func withGST(price int) int |
| func | the keyword that declares a function | func main() |
| Function declaration | the full definition: signature plus body | func area(l, w int) int { return l * w } |
| Parameter | a named input in the declaration, with a type | price int |
| Argument | the actual value passed in a call | 400 in withGST(400) |
| Call | running a function by writing its name and arguments | withGST(400) |
| Caller | the code that calls a function | main |
| Result / return value | the value a function gives back | 472 |
| Result type | the type(s) after the parameters | int, (int, int) |
| return | ends the function and sends results back | return price + price*18/100 |
| Signature | name, parameters and results: the function's contract | func share(laddoos, kids int) (int, int) |
| Function body | the block between the braces | { return l * w } |
| Package level | outside any function; where functions are declared | func withGST above main |
| Untyped constant ("number") | a literal like 100 with no fixed type yet |
have (number, number) |
| missing return | error: a function with results can end without returning | printing instead of returning |
| Multiple return values | a function returning several values | return each, left |
| Assignment mismatch | error: the number of variables ≠ number of values | each := share(10, 3) |
Blank identifier _ |
throws away a value you don't need | _, left := share(10, 3) |
| Named results | results with names, declared in the signature | (h, m, s int) |
| Zero value | the starting value of a variable with no value given | 0 for int |
| Naked return | return with no values; returns the named results |
toHMS |
| Variadic function | takes any number of values for its last parameter | func total(prices ...int) |
...T (collect) |
in a parameter list: any number of T, received as []T |
prices ...int |
s... (spread) |
after a slice in a call: pass its elements as separate arguments | total(cart...) |
| Slice | a list of values of one type (episodes 13-14) | []int{120, 80, 45} |
| len | the number of elements in a slice (or string, etc.) | len(nums) |
| Pass by value | arguments are copied into parameters; the caller's variable is untouched | discount(price) |
| Pointer | a value holding another variable's address (episode 11) | &price |
| Function type | the type of a function: its parameter and result types | func(int) int |
| Named function type | a name given to a function type | type offer func(int) int |
| Function value | a function used as a value: stored, passed, returned | best := tenPercent |
| Higher-order function | takes a function as a parameter or returns one | checkout(price int, o offer) |
| Function literal / anonymous function | a function written inline without a name (episode 10) | func(p int) int { return p } |
| %T | Printf verb that prints a value's type | func(int) int |
| nil function | the zero value of a function type; calling it panics | var f func() |
Summary
- A function is a named block you write once and call anywhere. Parameters are its inputs, arguments the values you pass,
returnsends back results. The signature is a contract Go checks at every call. - Go functions can return several values; catch them all, or skip some with
_. - Named results document meaning; a naked return returns them (keep it for short functions).
- Variadic
...intcollects any number of arguments into a slice;cart...spreads a slice into arguments. - Every argument is passed by value (copied). Return new values instead of changing parameters.
- Functions are values with function types: store them, pass them, return them. A function taking or returning a function is a higher-order function.
Next episode: closures, defer and recursion. A token counter that remembers its count, a file you forget to close, and a function that calls itself.