The unit of Go code
Go has no classes, so the function is the basic building block of every program. A few features make Go's functions unusually expressive without making them complicated.
A function can return several results. This is how Go reports errors (a value and an error, side by side, instead of exceptions), how lookups report whether they found anything, and how a single call can hand back a quotient and a remainder. Functions are values: they can be stored in variables, passed to other functions and returned from them, and a function literal can close over the variables around it. And defer schedules a call to run when the surrounding function returns, which puts clean-up code (closing a file, releasing a lock) right next to the code that needs it, where it is hard to forget.
Underneath all of this is one simple rule that explains a lot of Go's behaviour: every argument is passed by value, as a copy. When a function needs to change something that belongs to its caller, it is given a pointer, and the call site shows it with &.
Parameters, results and pointers
Definition— function declaration
func name(param Type, ...) ResultType { ... } declares a function. Consecutive parameters of the same type can share it: func divmod(a, b int). Several results are written in parentheses, (int, int), and may be named, (first, last string), in which case they are variables initialised to their zero values and a bare return returns their current values. A final parameter nums ...int is variadic: the function receives the arguments as a slice.
Definition— pointer
A pointer holds the address of a variable. &x takes the address of x (giving a *int if x is an int), and *p reads or writes the variable that p points to. The zero value of a pointer is nil. Go has no pointer arithmetic, and the garbage collector keeps a variable alive as long as any pointer to it exists, so returning the address of a local variable is perfectly safe.
package main
import (
"fmt"
"strings"
)
// Multiple results: the quotient and the remainder together.
func divmod(a, b int) (int, int) {
return a / b, a % b
}
// Named results document what is returned and start at their zero values.
func split(fullName string) (first, last string) {
parts := strings.Fields(fullName)
if len(parts) == 0 {
return // a "naked" return: returns first and last as they are
}
return parts[0], parts[len(parts)-1]
}
// Variadic: any number of ints, received as a slice.
func sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
// Go passes arguments by value; a pointer lets a function change the caller's variable.
func double(n *int) {
*n *= 2
}
func main() {
q, r := divmod(17, 5)
fmt.Println(q, r)
first, last := split("Ngũgĩ wa Thiong'o")
fmt.Printf("%q %q\n", first, last)
_, onlyLast := split("Zhang Wei")
fmt.Println(onlyLast)
fmt.Println(sum(), sum(1, 2, 3))
scores := []int{90, 85, 77}
fmt.Println(sum(scores...)) // spread a slice into variadic arguments
x := 21
double(&x) // &x is the address of x
fmt.Println(x)
}3 2
"Ngũgĩ" "Thiong'o"
Wei
0 6
252
42Some notes:
- Results are received with a multiple assignment,
q, r := divmod(17, 5). You must receive all of them; use_for the ones you don't need, as in_, onlyLast := split(...). - Named results are best used to document what a function returns when the types alone don't (two
strings could be anything). Nakedreturns are fine in very short functions and confusing in long ones, so most style guides use them sparingly. splitis a deliberately naive example. Real names don't divide neatly into "first" and "last": "Ngũgĩ wa Thiong'o" has a three-word family name, many cultures put the family name first, and many people have a single name. Production code usually stores a full name and, if needed, a separate "name to use in greetings".sum(scores...)passes a slice to a variadic function. You can't mix the two forms:sum(1, scores...)doesn't compile.double(&x)passes a pointer, so*n *= 2doubles the caller'sx. Without the pointer, the function would double its own copy and the caller would never know.
Function values and closures
package main
import (
"fmt"
"sort"
"strings"
)
// Functions are values: they can be stored, passed and returned.
type transform func(string) string
func applyAll(s string, steps ...transform) string {
for _, step := range steps {
s = step(s)
}
return s
}
// A closure captures variables from where it was created.
func counter() func() int {
n := 0
return func() int {
n++
return n
}
}
func exclaim(s string) string { return s + "!" }
func main() {
shout := applyAll(" karibu tena ", strings.TrimSpace, strings.ToUpper, exclaim)
fmt.Println(shout)
next := counter()
other := counter()
fmt.Println(next(), next(), next(), other())
// An anonymous function passed to the standard library.
cities := []string{"Quito", "Baku", "Lusaka", "Oslo", "Tbilisi"}
sort.Slice(cities, func(i, j int) bool {
if len(cities[i]) != len(cities[j]) {
return len(cities[i]) < len(cities[j])
}
return cities[i] < cities[j]
})
fmt.Println(cities)
// A closure that remembers results (memoisation).
memo := map[int]int{}
var fib func(int) int
fib = func(n int) int {
if n < 2 {
return n
}
if v, ok := memo[n]; ok {
return v
}
memo[n] = fib(n-1) + fib(n-2)
return memo[n]
}
fmt.Println(fib(50), len(memo))
}KARIBU TENA!
1 2 3 1
[Baku Oslo Quito Lusaka Tbilisi]
12586269025 49type transform func(string) stringnames a function type. Any function with that signature, includingstrings.TrimSpaceandstrings.ToUpperfrom the standard library and our ownexclaim, is atransformand can go in the list.counterreturns a closure: a function literal together with the variablenit refers to. Each call tocountercreates a freshn, which is whynextcounts 1, 2, 3 whileotherstarts again at 1. The variable lives on (the compiler moves it to the heap) for as long as the closure does. Closures are how Go expresses things that other languages do with small objects: callbacks, generators, configuration.sort.Slicetakes the slice and a "less" function that compares two positions. The closure readscitiesfrom the surrounding scope. Newer code often prefersslices.SortFuncfrom theslicespackage (lesson 4), whose comparison function receives the elements themselves.fibis declared withvarbefore it is assigned so that the function literal can call itself. Thememomap turns an exponential-time recursion into a linear one:fib(50)needs only 49 stored results instead of billions of calls.
Defer
Definition— defer
defer f(args) evaluates f and its arguments immediately but delays the call until the surrounding function returns, whether it returns normally, through an early return, or by panicking. Deferred calls run in last-in, first-out order. A deferred function literal can read and change the function's named results.
package main
import (
"errors"
"fmt"
)
func steps() {
defer fmt.Println("deferred 1")
defer fmt.Println("deferred 2")
fmt.Println("body")
} // deferred calls run here, last in, first out
func argumentsNow() {
x := 1
defer fmt.Println("deferred sees x =", x) // x is evaluated now
x = 2
fmt.Println("body sees x =", x)
}
// A deferred function can change named results: a common way to add context to errors.
func load(name string) (err error) {
defer func() {
if err != nil {
err = fmt.Errorf("loading %s: %w", name, err)
}
}()
if name == "" {
return errors.New("empty name")
}
return nil
}
type resource struct{ name string }
func open(name string) *resource {
fmt.Println("open", name)
return &resource{name}
}
func (r *resource) Close() { fmt.Println("close", r.name) }
func process() {
a := open("a.txt")
defer a.Close() // clean-up sits right next to acquisition
b := open("b.txt")
defer b.Close()
fmt.Println("working with", a.name, "and", b.name)
}
func main() {
steps()
argumentsNow()
fmt.Println(load("config"), "|", load(""))
process()
}body
deferred 2
deferred 1
body sees x = 2
deferred sees x = 1
<nil> | loading : empty name
open a.txt
open b.txt
working with a.txt and b.txt
close b.txt
close a.txtThe output shows each rule at work:
stepsprints "body" first; its deferred calls then run in reverse order of deferral.- In
argumentsNow, the deferredPrintlnprintsx = 1: the argument was evaluated when thedeferstatement ran, not when the deferred call ran. - In
load, the deferred closure inspects the named resulterrafterreturnhas set it and wraps it with context.%wkeeps the original error inside the new one, a technique lesson 6 explores. - In
process, eachCloseis deferred immediately after itsopen, so clean-up can't be forgotten on any path out of the function, and the files are closed in reverse order of opening, which is usually what dependent resources need. (The(r *resource) Close()syntax defines a method, the subject of lesson 5.)
The pattern f, err := os.Open(name); if err != nil { return err }; defer f.Close() appears in nearly every Go program that touches files, and mu.Lock(); defer mu.Unlock() in nearly every one that uses locks.
What a function call costs
Go's compiler does a few things behind the scenes that are worth knowing, because they explain both why idiomatic Go is fast and how to investigate when it isn't.
Inlining. Small functions, such as a one-line getter or exclaim above, are usually copied into their callers, so the call disappears entirely. You can write small, well-named helpers without worrying about call overhead.
Escape analysis. The compiler decides, for each variable, whether it can live on the function's stack (freed instantly when the function returns) or must escape to the heap (freed later by the garbage collector). A variable escapes when something might use it after the function returns: its address is returned, it is captured by a closure that outlives the call, or it is stored in a longer-lived structure. In counter, the variable n escapes because the returned closure keeps using it. Stack allocation is nearly free; heap allocation costs a little at allocation time and more in garbage-collection work. Running go build -gcflags=-m prints the compiler's decisions ("moved to heap: n"), and performance work on hot code paths often starts by reducing allocations there.
Growable stacks. Each goroutine (lesson 8) starts with a small stack of a few kilobytes, which the runtime grows by copying when a call chain needs more. That is why deep recursion rarely overflows in Go, and why a program can run hundreds of thousands of goroutines at once.
Function values and closures are a pointer to code plus, for closures, a pointer to the captured variables. Calling one is an indirect call, which the compiler usually cannot inline. In almost all code this is irrelevant; in a loop that runs a billion times, it may be worth noticing.
Example— Functional options: closures as configuration
A popular Go idiom uses closures to give constructors optional settings without default parameters. Each option is a function that modifies a configuration struct:
type Server struct {
addr string
timeout time.Duration
maxConn int
}
type Option func(*Server)
func WithTimeout(d time.Duration) Option { return func(s *Server) { s.timeout = d } }
func WithMaxConn(n int) Option { return func(s *Server) { s.maxConn = n } }
func NewServer(addr string, opts ...Option) *Server {
s := &Server{addr: addr, timeout: 30 * time.Second, maxConn: 100}
for _, opt := range opts {
opt(s)
}
return s
}Callers write NewServer(":8080") for the defaults or NewServer(":8080", WithTimeout(5*time.Second)) to change one setting. New options can be added later without breaking any existing call. The pattern combines three ideas from this lesson: function types, closures that capture their argument (d, n), and a variadic parameter. A plain options struct (NewServer(":8080", Config{Timeout: 5 * time.Second})) is the simpler alternative, and many teams prefer it; both are common in well-known libraries.
How Go programmers write functions
A few conventions show up in almost every Go codebase:
- Return errors last. A function that can fail returns
(result, error), with the error as the final value. Callers check it immediately. Lesson 6 is all about this. - The "comma ok" idiom. When a lookup can come up empty, the second result is a
boolnamedok:v, ok := memo[n]. You will see it with maps, type assertions and channel receives. - Accept interfaces, return concrete types. Parameters are often small interfaces (anything with a
Readmethod, say), so the function works with many types, while results are concrete structs, so callers get the full type. Lesson 5 shows why. - Keep functions short and flat. Early returns, small helpers, and no deep nesting. A function that doesn't fit on a screen is a candidate for splitting.
- Prefer explicit parameters to clever closures in exported APIs. Closures are excellent for callbacks and small helpers; but a struct with fields is easier to document, test and extend than a function that captures half a dozen variables.
- Be careful with
deferin loops. Deferred calls run when the function returns, not at the end of each iteration. A loop that opens a thousand files and defers eachClosekeeps all thousand open until the end; move the loop body into its own function so each file is closed promptly.
Why multiple results at all? Go's designers had spent decades with C, where a function that can fail must squeeze its error into the one return value (a -1, a NULL) or into a global variable such as errno, both easy to ignore and easy to misread. Exceptions, the other common answer, make failure invisible at the call site. Returning the error as an ordinary second value keeps it visible, cheap and local: you can see in every call whether it can fail, and the compiler complains if you assign the result and then never use it.
Go deliberately leaves out several features you may know from other languages: default parameter values, keyword arguments, function overloading, and (until generics) functions polymorphic over types. The usual substitutes are an options struct (Dial(addr, Options{Timeout: 5 * time.Second})), separate well-named functions (ParseInt, ParseFloat), and since Go 1.18, type parameters (lesson 7).
Common misconceptions
Misconception
"Go passes slices and maps by reference." Everything is passed by value. A slice value is a small header (a pointer to an array, a length, a capacity), and copying the header still points at the same array, so a function can change the elements. But it can't change the caller's length: append inside a function doesn't affect the caller's slice unless the new slice is returned. Lesson 4 explains this precisely.
Misconception
"Deferred calls see the latest values of their arguments." Arguments are evaluated when the defer statement executes. To see later values, defer a closure that reads the variables when it runs: defer func() { fmt.Println(x) }().
Misconception
"Returning a pointer to a local variable is dangerous, as in C." In Go it is safe and common: the compiler's escape analysis notices that the variable outlives the call and allocates it on the heap. return &resource{name} is idiomatic.
Misconception
"Closures in a loop all see the last value." That was true before Go 1.22 for loop variables, and you will find old code that works around it with i := i. Since Go 1.22 each iteration has its own variables, so closures capture the value from their own iteration.
Exercises
1. Functions, closures and defer
CoreComputationalWhat does calling this function print?
func deferLoop() {
for i := range 3 {
defer fmt.Print(i)
}
}
2. Functions, closures and defer
CoreComputationalWith counter from the lesson (each call returns a closure that counts 1, 2, 3, ...), what does this print?
c := counter()
c()
c()
d := counter()
fmt.Println(c(), d())
3. Functions, closures and defer
StretchComputationalWhat does fmt.Println(f()) print?
func f() (n int) {
defer func() { n *= 2 }()
return 5
}
4. Functions, closures and defer
CoreComputationalWhat does this print?
func inc(a [3]int) { a[0]++ }
func incSlice(s []int) { s[0]++ }
func main() {
arr := [3]int{1, 2, 3}
inc(arr)
sl := []int{1, 2, 3}
incSlice(sl)
fmt.Println(arr[0], sl[0])
}
5. Functions, closures and defer
CoreComputationalWith Go 1.22 or later, what does this print?
var fs []func() int
for i := range 3 {
fs = append(fs, func() int { return i })
}
for _, g := range fs {
fmt.Print(g())
}
6. Functions, closures and defer
Warm-upComputationalGiven func sum(nums ...int) int and s := []int{1, 2}, which call does not compile?