Thuta Learning
Go
IntermediateProgrammingBeginner

Functions

GoLesson 725 min

What you'll walk away with

  • Read and write a Go function signature with parameter and result types
  • Return two values, receive them with :=, and discard the unwanted one with _
  • Use the (value, error) shape for functions that can fail and check err != nil
  • Decide when named results and a ...T variadic parameter make a function clearer

Explain it simply

Explain it simply

A function is like a named recipe. You hand it ingredients (the parameters) and it hands back a dish (the return value). Once a recipe is written down you can cook it as often as you like, and once a function is written you can call it from as many places as you need.

Go's recipe card has two special features. First, every ingredient is labelled with its type. Second, a function can hand back more than one thing at once, such as the dish plus a note saying whether the cooking went well.

Problem → Why → Solution

The problem: is 0 an answer or a failure?

In languages where a function can return only one value, failure is often signalled with a special value such as 0 or -1. The divide() below returns 0 when you divide by zero. But the correct answer to divide(0, 5) is also 0, so the caller has no way to tell from the result what actually happened.

main.go
package main

import "fmt"

func divide(a, b int) int {
	if b == 0 {
		return 0 // failure... or a real answer?
	}
	return a / b
}

func main() {
	fmt.Println(divide(0, 5)) // 0 (correct)
	fmt.Println(divide(5, 0)) // 0 (actually a failure)
}

Why is this a problem?

When a failure hides inside an ordinary value, the caller easily forgets to check for it, and the wrong 0 ends up in a report or a database. Because a Go function can return two values, it can hand back the result and the "did it fail?" signal separately. In this lesson's example divide() returns (int, error), so the caller sees the error directly.

Core concept: signatures, multiple results and the error convention

A Go function is written with the func keyword, a name, a parameter list and its result types. The type comes after the parameter name: func add(x int, y int) int. When neighbouring parameters share a type you can shorten it to func add(x, y int) int. Result types follow the parameter list, and more than one result must be wrapped in parentheses: (int, error).

When a function returns two results you receive them with two variables: q, err := divide(10, 3). Writing q := divide(10, 3) with only one variable is a compile error: "assignment mismatch: 1 variable but divide returns 2 values". Use the blank identifier _ to discard a value you do not need. Go has no default parameter values and no function overloading, so each function name has exactly one signature.

For functions that can fail, Go's convention is to return an error as the last result. On success the error is nil; on failure it is a non-nil error value. The caller checks if err != nil straight away and only then uses the result. There are no exceptions, so the failure path is visible in the code.

Results can also be named: (quotient, remainder int). Named results are variables declared at the start of the function with their zero values, and a bare return hands back whatever they currently hold. When two results share a type, the names act as documentation. Keep bare returns for short functions, because in a long one it becomes hard to see what is actually returned.

Go passes arguments by value, which means the function receives a copy. Changing an int or a string inside the function does not change the caller's variable. This copy rule becomes important in the coming lessons when you pass arrays and structs around.

Mental model: copies in, results out
  1. Arguments are copied in
  2. Body returns on every path
  3. All results come back together
  4. Caller checks err first

Changes inside the function happen to copies; only the returned results travel back to the caller.

General pattern

go
func name(param1, param2 Type) Result {
	return value
}

func name(param Type) (Result, error) {
	if somethingWrong {
		return zeroValue, errors.New("what went wrong")
	}
	return value, nil
}

func name(values ...Type) (named1, named2 Type) { return }

Parameters of the same type can share one type name. Wrap more than one result in parentheses and put error last. ...Type accepts any number of arguments, and named results can be returned with a bare return.

Example: four kinds of function

This program has add(), which returns one result; divide(), which returns a result and an error; divmod(), which uses named results; and sum(), which accepts any number of arguments. main() calls each one and shows how its results are received.

main.go
package main

import (
	"errors"
	"fmt"
)

func add(x, y int) int {
	return x + y
}

func divide(a, b int) (int, error) {
	if b == 0 {
		return 0, errors.New("division by zero")
	}
	return a / b, nil
}

func divmod(a, b int) (quotient, remainder int) {
	quotient = a / b
	remainder = a % b
	return
}

func sum(nums ...int) int {
	total := 0
	for _, n := range nums {
		total += n
	}
	return total
}

func main() {
	fmt.Println(add(42, 13))

	q, err := divide(10, 3)
	fmt.Println(q, err)

	if _, err := divide(1, 0); err != nil {
		fmt.Println("error:", err)
	}

	q, r := divmod(17, 5)
	fmt.Println(q, r)

	fmt.Println(sum(1, 2, 3), sum())
}

Code breakdown

  1. Shared typefunc add(x, y int) int {

    x and y are both int, so the type is written once. The int after the ) is the result type.

  2. Result plus errorfunc divide(a, b int) (int, error) {

    Two results, so they sit in parentheses. When b == 0 it returns 0 with errors.New("division by zero"); on success the error slot is nil.

  3. Receive bothq, err := divide(10, 3)

    Both results are received. 10 / 3 is integer division, so q is 3, and err is nil, which prints as "3 <nil>".

  4. Check the errorif _, err := divide(1, 0); err != nil {

    The quotient is discarded with _ and only err is checked. Declared in the if's short statement, this err lives only inside the if block.

  5. Named resultsfunc divmod(a, b int) (quotient, remainder int) {

    quotient and remainder start as 0. The body fills them in and the bare return hands both back, so divmod(17, 5) gives 3 2.

  6. Variadicfunc sum(nums ...int) int {

    ...int gathers the int arguments into nums, a []int. Calling sum() with no arguments gives an empty nums and returns 0.

You should see
55
3 <nil>
error: division by zero
3 2
6 0

Functions are values too: closures

In Go a function can be stored in a variable, passed as an argument and returned. func(int) int is the type of "a function that takes an int and returns an int". counter() returns a function that remembers the count variable from its surroundings; that is called a closure. Each call to next() increases the same count.

closure.go
package main

import "fmt"

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

func apply(nums []int, fn func(int) int) []int {
	out := make([]int, 0, len(nums))
	for _, n := range nums {
		out = append(out, fn(n))
	}
	return out
}

func main() {
	next := counter()
	fmt.Println(next(), next(), next()) // 1 2 3

	double := func(n int) int { return n * 2 }
	fmt.Println(apply([]int{1, 2, 3}, double)) // [2 4 6]
}

In real projects

Where this shows up in real projects

Open the Go standard library and you will find the (value, error) shape everywhere. strconv.Atoi("42") returns (int, error), and os.Open(name) returns (*os.File, error). HTTP handlers, database queries and config loaders all follow the same pattern. That is why Go code is full of if err != nil { return ..., err } lines: the error is passed back up to a caller that logs it or turns it into an HTTP 400 response.

You already use a variadic function every day: fmt.Println(a ...any) accepts any number of arguments. Function values appear when you hand a comparison to sort.Slice(items, func(i, j int) bool {...}), register a route with http.HandleFunc("/", handler), or wrap handlers in middleware. In a team, small functions with clear signatures are easy to unit test and quick to review.

Common mistakes

Common mistakes

1. Forgetting a return on one path

func isAdult(age int) bool { if age >= 18 { return true } } fails to compile with "missing return". Once a result type is declared, every path that can reach the end of the function needs a return. Writing return age >= 18 on one line is the cleanest fix.

2. Throwing the error away with _

n, _ := strconv.Atoi(input) compiles, but when the user types "abc" n is 0 and the program carries on as if nothing happened, which is exactly the problem from the start of this lesson. Always check the error, and if you cannot handle it here, return it to the caller.

3. Expecting a function to change the caller's variable

Calling func reset(n int) { n = 0 } as reset(score) leaves score unchanged, because the function only changed its copy. Return the new value and store it, as in score = reset(score), or use a pointer, which a later lesson covers.

Best practices

Best practices

  • Give each function one job and a verb name (parsePrice, sendEmail).
  • Put error last, and return zero values for the other results when you return an error.
  • Use named results only when results share a type and the names add meaning.
  • When a function needs five or six parameters, consider grouping them in a struct.

Mini challenge

Mini challenge: average and grade

Write two functions that turn a student's scores into an average and a letter grade. With no scores, the average must return an error.

  • average(scores ...int) (float64, error) returns errors.New("no scores") when there are none
  • grade(avg float64) string gives A from 90, B from 80, otherwise C
  • main() tries (95, 88, 92), (70, 85) and a call with no arguments
  • Check the error with err != nil instead of discarding it with _
grades.go
package main

import (
	"errors"
	"fmt"
)

func average(scores ...int) (float64, error) {
	// TODO: return an error when len(scores) == 0
	// TODO: add the scores and divide as float64
	return 0, errors.New("not implemented")
}

func grade(avg float64) string {
	// TODO: "A" from 90, "B" from 80, otherwise "C"
	return ""
}

func main() {
	// TODO: print "%.1f %s %v" for (95, 88, 92) and (70, 85)
	// TODO: call average() with no scores and print the error
	fmt.Println("todo")
}

Expected: 91.7 A <nil> 77.5 C <nil> error: no scores

Show hint

Dividing two ints drops the fraction, so convert first: float64(total) / float64(len(scores)). In grade(), two ifs and three returns are enough.

Show solution
grades.go
package main

import (
	"errors"
	"fmt"
)

func average(scores ...int) (float64, error) {
	if len(scores) == 0 {
		return 0, errors.New("no scores")
	}
	total := 0
	for _, s := range scores {
		total += s
	}
	return float64(total) / float64(len(scores)), nil
}

func grade(avg float64) string {
	if avg >= 90 {
		return "A"
	}
	if avg >= 80 {
		return "B"
	}
	return "C"
}

func main() {
	avg, err := average(95, 88, 92)
	fmt.Printf("%.1f %s %v\n", avg, grade(avg), err)

	avg, err = average(70, 85)
	fmt.Printf("%.1f %s %v\n", avg, grade(avg), err)

	if _, err := average(); err != nil {
		fmt.Println("error:", err)
	}
}

Quick quiz 1 / 3

Given func divide(a, b int) (int, error), which line does NOT compile?

Quick quiz 2 / 3

With func split(n int) (half, rest int) { half = n / 2; rest = n - half; return }, what does split(7) return?

Quick quiz 3 / 3

How should a Go function that turns user input into a number be designed?

What to remember

  • In Go the type follows the parameter name, and same-typed parameters can share it: func add(x, y int).
  • A function can return several results; the caller must receive them all and discards unwanted ones with _.
  • Functions that can fail return error last, and the caller checks if err != nil right away.
  • Named results, ...T variadic parameters and function values make functions clearer and more flexible.

A Tour of Go — Go

Updated on

Progress is saved only in this browser on this device. It isn't synced to other devices.

Report a problem with this lessonOpens your email app with this lesson's address filled in — nothing is sent until you send it.

Functions | Thuta Learning