Functions, multiple returns and defer
Course contents (17 lessons)
- Getting started with Go
- Installing Go 1.25 and your first program
- Variables, types and constants
- Control flow: if, for and switch
- Functions, multiple returns and defer
- Slices and maps
- Arrays and slices
- Maps and working with strings
- Structs, methods and interfaces
- Structs, methods and pointers
- Interfaces
- Errors, packages and generics
- Error handling the Go way
- Packages and modules
- Generics
- Concurrency
- Goroutines and channels
- select, timeouts and context
- Mutexes, sync and the race detector
- Testing
- Testing and benchmarks
- Building and shipping a service
- Building an HTTP JSON API with net/http
- Building and deploying a Go service
Functions are where Go gets practical
A function in Go has a name, typed parameters and an optional return type. Types come after the names, which looks backwards if you come from C or Java, but you get used to it within a day.
func add(a int, b int) int {
return a + b
}
func add3(a, b, c int) int { // same type shared by neighbours
return a + b + c
}
Multiple return values
A Go function can return more than one value. This is the single most important feature to understand early, because it is how Go reports errors. There are no exceptions. A function that can fail returns its result and an error, and the caller checks it.
package main
import (
"errors"
"fmt"
"strings"
)
func splitBill(total float64, people int) (float64, error) {
if people < 1 {
return 0, errors.New("people must be at least 1")
}
return total / float64(people), nil
}
func stats(values ...float64) (min, max, avg float64) {
if len(values) == 0 {
return
}
min, max = values[0], values[0]
sum := 0.0
for _, v := range values {
if v < min {
min = v
}
if v > max {
max = v
}
sum += v
}
avg = sum / float64(len(values))
return
}
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func describe(name string) string {
defer fmt.Println("describe finished for", name)
return "item: " + strings.ToUpper(name)
}
func main() {
share, err := splitBill(3000, 4)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("each pays %.2f\n", share)
if _, err := splitBill(3000, 0); err != nil {
fmt.Println("error:", err)
}
lo, hi, avg := stats(250, 400, 175)
fmt.Println(lo, hi, avg)
next := makeCounter()
fmt.Println(next(), next(), next())
fmt.Println(describe("tea"))
}
Output:
each pays 750.00
error: people must be at least 1
175 400 275
1 2 3
describe finished for tea
item: TEA
The (value, error) pattern
When splitBill fails, it returns a zero value and a non-nil error. When it works, it returns the answer and nil. The caller always checks if err != nil right away. You will type this line thousands of times. It looks repetitive, but it makes the failure path visible in the code. The convention is that the error is the last return value. If you do not care about one of the results, assign it to _, as in _, err := .... Ignoring the error itself, though, is a bug waiting to happen.
Named results and variadic parameters
stats shows two more features. The parameter values ...float64 is variadic: callers pass any number of floats, and inside the function values is a slice. To pass an existing slice, write stats(mySlice...). The results (min, max, avg float64) are named, so they exist as variables from the start, and a bare return sends their current values back. Named results are good for documentation in short functions. In long functions a bare return makes code harder to follow, so use explicit returns there.
Note that min and max are also built-in functions since Go 1.21. Our named results hide them inside stats, which is legal but a bit confusing. In real code I would choose other names, such as lowest and highest.
Closures and first-class functions
Functions are values. You can store them in variables, pass them as arguments and return them. makeCounter returns a function that remembers its own count. Each call to makeCounter creates a separate counter. This is useful for callbacks, middleware and small stateful helpers.
defer
A defer statement schedules a call to run when the surrounding function returns, whichever way it leaves. This is how Go does cleanup: closing files, unlocking mutexes, ending timers.
f, err := os.Open("data.txt")
if err != nil {
return err
}
defer f.Close() // runs when this function returns
// ... use f
Put the defer directly after the successful open so that you never forget it. Deferred calls run in last-in, first-out order. A subtle point: the arguments of a deferred call are evaluated immediately, when the defer line runs, not when the function exits.
Common mistakes
- Not checking errors. The compiler will not stop you from ignoring a returned error. Linters like
go vetandstaticcheckcatch some cases. - Deferring in a loop. Defers run when the function ends, not at the end of each iteration, so opening many files in a loop and deferring each close keeps all of them open. Move the body into its own function.
- Variable shadowing of err. Writing
x, err := f()inside an inner block creates a newerrand the outer one is untouched. - Returning a partially valid result with an error and expecting callers to use it. By convention, if the error is not nil, ignore the other values.
Try it yourself
Write parsePrice(text string) (float64, error) that uses strconv.ParseFloat and returns an error for negative numbers. Call it with three inputs: a valid one, a non-number and a negative. Then write a variadic sum(nums ...int) int and call it with a slice. Finish with a function that returns a closure which applies a discount percentage.
package main
import (
"errors"
"fmt"
"strings"
)
func splitBill(total float64, people int) (float64, error) {
if people < 1 {
return 0, errors.New("people must be at least 1")
}
return total / float64(people), nil
}
func stats(values ...float64) (min, max, avg float64) {
if len(values) == 0 {
return
}
min, max = values[0], values[0]
sum := 0.0
for _, v := range values {
if v < min {
min = v
}
if v > max {
max = v
}
sum += v
}
avg = sum / float64(len(values))
return
}
func makeCounter() func() int {
count := 0
return func() int {
count++
return count
}
}
func describe(name string) string {
defer fmt.Println("describe finished for", name)
return "item: " + strings.ToUpper(name)
}
func main() {
share, err := splitBill(3000, 4)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("each pays %.2f\n", share)
if _, err := splitBill(3000, 0); err != nil {
fmt.Println("error:", err)
}
lo, hi, avg := stats(250, 400, 175)
fmt.Println(lo, hi, avg)
next := makeCounter()
fmt.Println(next(), next(), next())
fmt.Println(describe("tea"))
}
This course is free to read. Create a free account to enrol, save your progress and pick up where you left off.
Sign up free I already have an account