BeginnerLesson 3 of 155 min read

Control Flow and Functions: Multiple Returns, defer and Closures

Learn Go's for, if and switch, functions with multiple return values, variadic parameters, closures and defer, and see the real order in which deferred calls run.

In this lesson you will

  • Use for, if and switch
  • Return multiple values
  • Write variadic functions and closures
  • Predict the order of defer

About 28 minutes

Weights, delays and a deferred cleanup

Mei’s program totals the weight of parcels, finds the heaviest, converts delivery times and always has to close a log file, whatever happens. Go’s control flow is deliberately small: there is only one loop keyword, for, and it does the work of while and foreach too. Functions can return several values, which is how Go reports errors without exceptions, and defer schedules a call for when the function returns, which makes cleanup hard to forget.

The for loop has three forms: for init; condition; post for counting, for condition for a while loop, and for range over a slice, string, map or channel. An if statement can start with a short statement, as in if v, ok := m[k]; ok, which scopes the variable to the if. A switch has no fall-through by default, cases can be expressions, and a switch with no tag works as a tidy chain of ifs. A function that returns more than one value lists the types in parentheses, and a variadic parameter, written …int, collects any number of arguments into a slice. A closure is a function that captures variables from its surroundings and keeps them alive. Deferred calls run when the surrounding function returns, in last-in, first-out order, and their arguments are evaluated when the defer statement is executed.

Feature Syntax
Counting loop for i := 0; i < n; i++ { }
While loop for cond { }
Range for i, v := range xs { }
Multiple returns func minmax(xs []float64) (float64, float64)
Variadic func sum(xs …int) int
Defer defer f.Close()
package main

import "fmt"

func minmax(xs []float64) (lo, hi float64) {
	lo, hi = xs[0], xs[0]
	for _, x := range xs[1:] {
		if x < lo {
			lo = x
		}
		if x > hi {
			hi = x
		}
	}
	return
}

func sum(xs ...int) int {
	t := 0
	for _, x := range xs {
		t += x
	}
	return t
}

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

func classify(kg float64) string {
	switch {
	case kg < 1:
		return "light"
	case kg < 10:
		return "normal"
	default:
		return "heavy"
	}
}

func deferred() {
	for i := 1; i <= 3; i++ {
		defer fmt.Println("deferred call", i)
	}
	x := 10
	defer fmt.Println("x was", x, "when the defer ran its statement")
	x = 99
	fmt.Println("function body ends, x is", x)
}

func main() {
	w := []float64{0.4, 2.5, 12.0, 7.25, 0.9, 3.0}
	lo, hi := minmax(w)
	fmt.Println("lightest", lo, "heaviest", hi)
	fmt.Println("sum of 1..5 =", sum(1, 2, 3, 4, 5), "| sum of nothing =", sum(), "| spread slice =", sum([]int{10, 20}...))
	next := counter()
	fmt.Println("closure counter:", next(), next(), next())
	counts := map[string]int{}
	for _, kg := range w {
		counts[classify(kg)]++
	}
	fmt.Println("classes:", counts["light"], counts["normal"], counts["heavy"])
	total, steps := 0, 0
	for total < 100 {
		total += 7
		steps++
	}
	fmt.Println("for as while: reached", total, "after", steps, "steps")
	deferred()
}
lightest 0.4 heaviest 12
sum of 1..5 = 15 | sum of nothing = 0 | spread slice = 30
closure counter: 1 2 3
classes: 2 3 1
for as while: reached 105 after 15 steps
function body ends, x is 99
x was 10 when the defer ran its statement
deferred call 3
deferred call 2
deferred call 1

The function minmax returned two values, the lightest parcel 0.4 and the heaviest 12, and it used named results, so a bare return sends them back. The variadic sum added five numbers to 15, nothing to 0, and a slice spread with the three dots to 30. The closure kept its own counter between calls, giving 1, 2, 3, which is state hidden inside a function. The switch without a tag classified the six parcel weights into 2 light, 3 normal and 1 heavy, and the single for keyword served as a while loop, ending at 105 after 15 steps.

The defer experiment shows the order. The function body printed that x is 99 and ended, and then the deferred calls ran in reverse order: the last one registered ran first, so “x was 10…” came first, then “deferred call 3”, then 2, then 1. Notice that the deferred Println printed x as 10, not 99, because the arguments of a deferred call are evaluated when the defer statement runs, not when the call is made. This last-in, first-out behaviour is what makes defer ideal for cleanup: you open a file, defer its close on the next line, and every exit path closes it.

Check by hand: the six weights [0.4, 2.5, 12.0, 7.25, 0.9, 3.0] include one below 1 kilogram twice (0.4 and 0.9), so light has 2; normal has 2.5, 7.25 and 3.0, which is 3; and heavy has the single 12.0. The sum 1 + 2 + 3 + 4 + 5 is 15. The loop reaches 15 x 7 = 105. Python classified the same weights with the same rules and agreed.

defer in a loop waits for the function to end

A defer inside a loop does not run at the end of each iteration, but when the whole function returns. For per-iteration cleanup, put the loop body in its own function.

Defer right after you acquire

Write f, err := os.Open(name), check the error, and on the next line defer f.Close(). Then no later return can forget to close it.

About this course

Every program in this lesson was built and run with Go 1.24 while the course was written. Go releases twice a year, so check go.dev for the current version and release notes.

Practice

Write a function that returns the average and the count of a slice. Write a variadic max that panics on no arguments and think about whether that is the right design. Use a closure to make a function that adds a fixed delay to a time.

Check what you learned

Five quick questions. Pick an answer and you will see straight away whether it is right and why.

What does the for keyword cover in Go?

  1. Only counting
  2. Only ranges
  3. Only infinite loops
  4. Counting, while and range loops

Go has one loop keyword.

In which order do deferred calls run?

  1. First in, first out
  2. Random
  3. Last in, first out
  4. Alphabetical

3, 2, 1.

When are a deferred call’s arguments evaluated?

  1. When the function returns
  2. Never
  3. When the defer statement runs
  4. At compile time

x was 10, not 99.

What does …int in a parameter list mean?

  1. A pointer
  2. Any number of int arguments
  3. A range
  4. A channel

They arrive as a slice.

What is a closure?

  1. A closed file
  2. A function that captures variables from its surroundings
  3. A loop
  4. A package

The counter kept its state.

Summary

  • Go has a single loop keyword, for.
  • Functions can return multiple values and take variadic parameters.
  • Closures capture variables.
  • defer runs in last-in, first-out order with arguments evaluated early.

Next lesson

Lesson 4 covers slices and maps.

Questions

Does Go have exceptions?

No. Functions return errors as values, and panic and recover exist for exceptional cases. Lesson 6 covers errors in detail.

Is there a ternary operator?

No. Use an if statement. The language prefers one clear way to do things.

What is a named result?

A result that has a name in the function signature, which acts like a local variable, and a bare return sends the current values back.

Progress is saved in this browser.