Lesson 9 of 20 · Part 3: Functions
Functions
Learn Go functions for beginners. Parameters and return values, multiple returns, variadic functions, function values, closures, recursion and defer, with examples.
5 min read · Updated · Beginner friendly
What you'll learn
- Write functions with parameters and return values
- Return multiple values and use variadic parameters
- Treat functions as values and build closures
- Use recursion and defer
Up to now all your code has lived inside main. As programs grow, you want to give a piece of logic a name, reuse it, and test it on its own. That’s what functions are for. You have already called many functions, like fmt.Println and strings.ToUpper; now you’ll write your own.
Declaring a function
package main
import "fmt"
func greet(name string) {
fmt.Println("Hello,", name)
}
func add(a int, b int) int {
return a + b
}
func main() {
greet("Gopher")
greet("Ada")
total := add(3, 4)
fmt.Println("3 + 4 =", total)
}Hello, Gopher
Hello, Ada
3 + 4 = 7A function declaration has four parts:
- the keyword
func, - a name (
add), - a list of parameters with their types, in parentheses (
a int, b int), - the result type after the parentheses (
int), if the function returns something.
return hands a value back to the caller and ends the function. When several parameters in a row share a type, you can write it once: func add(a, b int) int.
The order of functions in a file doesn’t matter: main can call a function that is defined below it.
Arguments are copied
When you call a function, Go copies each argument into the parameter. Changing the parameter inside the function doesn’t change the caller’s variable:
package main
import "fmt"
func double(n int) {
n = n * 2
fmt.Println("inside:", n)
}
func main() {
x := 5
double(x)
fmt.Println("outside:", x)
}inside: 10
outside: 5This is called pass by value. To let a function change the caller’s variable, you pass a pointer, which is the topic of the next lesson. The usual and clearer alternative is simply to return the new value.
Multiple return values
A Go function can return more than one value. This is used everywhere, most often to return a result and an error:
package main
import "fmt"
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, fmt.Errorf("cannot divide %v by zero", a)
}
return a / b, nil
}
func minMax(nums []int) (int, int) {
lo, hi := nums[0], nums[0]
for _, n := range nums {
lo = min(lo, n)
hi = max(hi, n)
}
return lo, hi
}
func main() {
result, err := divide(10, 4)
fmt.Println(result, err)
_, err = divide(1, 0)
fmt.Println("error:", err)
lo, hi := minMax([]int{8, 3, 12, 5})
fmt.Println("min:", lo, "max:", hi)
}2.5 <nil>
error: cannot divide 1 by zero
min: 3 max: 12Use _ to ignore a return value you don’t need. min and max are built-in functions in Go 1.21 and later. Lesson 11 covers errors properly.
Named results
You can give the results names. They start as zero values, and a bare return returns their current values:
package main
import "fmt"
func split(total int) (quotient, remainder int) {
quotient = total / 3
remainder = total % 3
return
}
func main() {
q, r := split(17)
fmt.Println(q, r)
}5 2Named results document what a function returns. Bare return statements make long functions harder to read, though, so use them only in short functions.
Variadic functions
A variadic function accepts any number of arguments of one type. Put ... before the type of the last parameter; inside the function it is a slice:
package main
import "fmt"
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
func main() {
fmt.Println(sum())
fmt.Println(sum(1, 2, 3))
scores := []int{10, 20, 30, 40}
fmt.Println(sum(scores...)) // spread an existing slice with ...
}0
6
100fmt.Println itself is variadic, which is why it accepts any number of values.
Functions are values
In Go, a function is a value like any other. You can store it in a variable, put it in a map, and pass it to another function:
package main
import (
"fmt"
"strings"
)
func apply(words []string, transform func(string) string) []string {
var result []string
for _, w := range words {
result = append(result, transform(w))
}
return result
}
func shout(s string) string {
return strings.ToUpper(s) + "!"
}
func main() {
words := []string{"go", "is", "fun"}
fmt.Println(apply(words, shout))
fmt.Println(apply(words, strings.ToUpper)) // pass an existing function by name
// an anonymous function, written in place
fmt.Println(apply(words, func(s string) string {
return "<" + s + ">"
}))
}[GO! IS! FUN!]
[GO IS FUN]
[<go> <is> <fun>]The type func(string) string means “a function that takes a string and returns a string”. A function without a name, like the last one, is an anonymous function (or function literal). You used one in lesson 8 with slices.SortFunc.
Closures
An anonymous function can use variables from the code around it, and it keeps them alive even after that code has finished. Such a function is called a closure:
package main
import "fmt"
func counter() func() int {
count := 0
return func() int {
count++
return count
}
}
func main() {
next := counter()
fmt.Println(next(), next(), next())
other := counter() // a fresh count
fmt.Println(other(), next())
}1 2 3
1 4Each call to counter creates a new count variable, and the returned function “closes over” its own copy. Closures are useful for generators, callbacks, and keeping state without a global variable.
Recursion
A function can call itself. This is recursion, and it’s a natural fit for problems that are defined in terms of smaller versions of themselves:
package main
import "fmt"
// factorial returns n! = n × (n-1) × … × 1
func factorial(n int) int {
if n <= 1 {
return 1 // the base case stops the recursion
}
return n * factorial(n-1)
}
func fib(n int) int {
if n < 2 {
return n
}
return fib(n-1) + fib(n-2)
}
func main() {
fmt.Println("5! =", factorial(5))
for i := range 10 {
fmt.Print(fib(i), " ")
}
fmt.Println()
}5! = 120
0 1 1 2 3 5 8 13 21 34 Every recursive function needs a base case that returns without recursing. Without one, the function calls itself forever until the program crashes with a stack overflow.
defer: run this at the end
defer schedules a function call to run just before the surrounding function returns, no matter how it returns. It’s used for clean-up, such as closing a file you have opened:
package main
import "fmt"
func main() {
fmt.Println("open the file")
defer fmt.Println("close the file") // runs last
fmt.Println("read the file")
fmt.Println("process the data")
}open the file
read the file
process the data
close the filePlacing the clean-up right next to the setup makes it hard to forget. If you defer several calls, they run in reverse order: last in, first out.
package main
import "fmt"
func main() {
for i := range 3 {
defer fmt.Println("deferred", i)
}
fmt.Println("done looping")
}done looping
deferred 2
deferred 1
deferred 0The arguments of a deferred call are evaluated immediately, when the defer line runs, even though the call happens later.
Common mistakes
Missing return. If a function declares a result type, every path through it must end in return. The compiler reports missing return.
Expecting a function to change its arguments. Arguments are copies. Return the new value, or pass a pointer (next lesson).
Recursion without a base case. Always check that your recursive function has an input for which it stops.
Exercises
1. Is it a palindrome? Write isPalindrome(s string) bool that reports whether a word reads the same backwards, and test it with "level" and "gopher".
Show solution
package main
import "fmt"
func isPalindrome(s string) bool {
for i, j := 0, len(s)-1; i < j; i, j = i+1, j-1 {
if s[i] != s[j] {
return false
}
}
return true
}
func main() {
fmt.Println(isPalindrome("level"), isPalindrome("gopher"))
}true falseThis compares bytes, which works for plain English text. For any Unicode text, convert to []rune(s) first.
2. Average. Write a variadic average(nums ...float64) float64 that returns 0 when called with no numbers.
Show solution
package main
import "fmt"
func average(nums ...float64) float64 {
if len(nums) == 0 {
return 0
}
total := 0.0
for _, n := range nums {
total += n
}
return total / float64(len(nums))
}
func main() {
fmt.Println(average(4, 8, 15, 16, 23, 42))
fmt.Println(average())
}18
03. Filter. Write filter(nums []int, keep func(int) bool) []int and use it with an anonymous function to keep only the numbers greater than 10 from []int{3, 14, 7, 21, 10, 11}.
Show solution
package main
import "fmt"
func filter(nums []int, keep func(int) bool) []int {
var out []int
for _, n := range nums {
if keep(n) {
out = append(out, n)
}
}
return out
}
func main() {
nums := []int{3, 14, 7, 21, 10, 11}
big := filter(nums, func(n int) bool { return n > 10 })
fmt.Println(big)
}[14 21 11]4. Sum of digits, recursively. Write a recursive digitSum(n int) int, so that digitSum(9875) returns 29.
Show solution
package main
import "fmt"
func digitSum(n int) int {
if n < 10 {
return n
}
return n%10 + digitSum(n/10)
}
func main() {
fmt.Println(digitSum(9875))
}29Recap
func name(params) results { ... }declares a function;returnhands back values.- Arguments are copied (pass by value).
- Functions can return several values, typically a result and an
error. ...Tmakes a function variadic;slice...spreads a slice into it.- Functions are values: pass them around, write them inline, and build closures.
- Recursion needs a base case;
deferruns clean-up when the function returns, in reverse order.
Next, you will learn what pointers are and when to use them.
Finished this lesson?
Your progress is saved in this browser only.