Course › Week 1 · Basics and a first CLI › Day 3 · lesson 3 of 42 · 20 min reading + 45–60 min practice
Functions and errors
Functions that return two values, and errors as ordinary values you check with if err != nil.
On this page
Go has no exceptions. A function that can fail returns its result and an error, and the caller checks the error right there, on the next line. It is the single most visible difference from PHP, and you will write it hundreds of times.
Today: functions, functions that return two values, the error type, making your own errors, and the shape every Go function that can fail ends up with.
Functions
1. Parameters and a result
func, the name, the parameters with their types, then the result type. As with variables, the type comes after the name.
package main
import "fmt"
func totalCents(nights int, nightlyCents int) int {
return nights * nightlyCents
}
func main() {
fmt.Println(totalCents(3, 12950))
}
38850Every parameter and the result have a type, always: there is no untyped parameter in Go. When parameters next to each other share a type, you can write it once: func totalCents(nights, nightlyCents int) int. Both forms mean the same.
Functions sit at the top level of the file, and the order does not matter: main can call a function written below it.
2. Two results
A function can return more than one value. List the types in parentheses, and return them separated by commas.
package main
import "fmt"
func weeksAndDays(nights int) (int, int) {
return nights / 7, nights % 7
}
func main() {
weeks, days := weeksAndDays(17)
fmt.Printf("%d weeks and %d days\n", weeks, days)
}
2 weeks and 3 daysThe caller receives both into two variables with one :=. In PHP you would return an array and destructure it with [$weeks, $days] = …; in Go the two results are typed and the compiler checks you take both.
3. You must take every result
Asking for one variable when a function returns two is an error:
package main
import "fmt"
func weeksAndDays(nights int) (int, int) {
return nights / 7, nights % 7
}
func main() {
weeks := weeksAndDays(17)
fmt.Println(weeks)
}
# hello
./main.go:10:11: assignment mismatch: 1 variable but weeksAndDays returns 2 valuesWhen you really need only one of them, take the other into _, the blank identifier: weeks, _ := weeksAndDays(17). _ is a name that throws the value away, and writing it is a visible decision.
Errors are values
4. A function that can fail
strconv.Atoi turns text into an int. The text may not be a number, so it returns two things: the number, and an error.
package main
import (
"fmt"
"strconv"
)
func main() {
nights, err := strconv.Atoi("3")
fmt.Println(nights, err)
nights, err = strconv.Atoi("three")
fmt.Println(nights, err)
}
3 <nil>
0 strconv.Atoi: parsing "three": invalid syntaxerror is a type, like int. When the call worked, the error is nil, Go’s “nothing”. When it failed, the error is a value that describes the problem, and printing it prints that description. The number is then 0, its zero value, and means nothing.
The second call uses =, not :=: both variables already exist. strconv is the standard package for converting strings to and from numbers and booleans. Atoi is short for “ASCII to integer”.
5. if err != nil
The rule: check the error before you touch the result. This is the line you will type most in Go.
package main
import (
"fmt"
"strconv"
)
func main() {
nights, err := strconv.Atoi("three")
if err != nil {
fmt.Println("cannot read the number of nights:", err)
return
}
fmt.Println("nights:", nights)
}
cannot read the number of nights: strconv.Atoi: parsing "three": invalid syntaxreturn in main ends the program. The successful path continues below the if, not inside an else: handle the failure, leave, and keep the main line of the code flat on the left.
If you take err and never read it, the compiler stops you: it is an unused variable. But you can still throw an error away, by taking it into _ or by calling a function as a plain statement and ignoring everything it returns. Nothing stops that, so it is a rule you keep yourself, and the one Go reviewers look for first. On this site, every error is checked.
6. Your own errors
Return an error from your function with errors.New for a fixed message, or fmt.Errorf for a message with values in it. Return nil when there was no problem.
package main
import (
"errors"
"fmt"
)
const maxGuests = 6
func checkGuests(guests int) error {
if guests < 1 {
return errors.New("a booking needs at least one guest")
}
if guests > maxGuests {
return fmt.Errorf("%d guests is more than the %d this flat allows", guests, maxGuests)
}
return nil
}
func main() {
err := checkGuests(2)
fmt.Println("2 guests:", err)
err = checkGuests(0)
fmt.Println("0 guests:", err)
err = checkGuests(9)
fmt.Println("9 guests:", err)
}
2 guests: <nil>
0 guests: a booking needs at least one guest
9 guests: 9 guests is more than the 6 this flat allowsA function that only checks returns just an error. Printed, nil shows as <nil>.
Error messages start lowercase and do not end with a period, because callers often add their own words in front: rejected: a booking needs at least one guest.
7. if with a short statement
if can run one short statement before its condition, separated by a semicolon. The variable it creates exists only inside that if and its else.
package main
import (
"errors"
"fmt"
)
func checkGuests(guests int) error {
if guests < 1 {
return errors.New("a booking needs at least one guest")
}
return nil
}
func main() {
if err := checkGuests(0); err != nil {
fmt.Println("rejected:", err)
return
}
fmt.Println("accepted")
}
rejected: a booking needs at least one guestIt is the usual way to call a function that returns only an error: the err does not linger in the rest of main, so the next call can create its own.
The shape of a function that can fail
8. Result and error together
Most functions you write return a value and an error, with the error last. On failure, return the zero value with the error; on success, the value with nil.
package main
import (
"fmt"
"strconv"
)
const maxGuests = 6
func parseGuests(text string) (int, error) {
guests, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("guests must be a number, got %q", text)
}
if guests < 1 || guests > maxGuests {
return 0, fmt.Errorf("guests must be between 1 and %d, got %d", maxGuests, guests)
}
return guests, nil
}
func report(input string) {
guests, err := parseGuests(input)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("guests:", guests)
}
func main() {
report("4")
report("four")
report("12")
}
guests: 4
error: guests must be a number, got "four"
error: guests must be between 1 and 6, got 12|| is “or” and && is “and”, as in PHP. parseGuests reads top to bottom: each check that fails returns at once, and the last line is the success. report has no result type at all: a function that returns nothing just leaves it out, and return stops it early.
Here the error from strconv.Atoi is replaced by a clearer message of our own, so the original detail is lost. Wrapping errors keeps both; Week 2 covers it.
Coming from PHP
<?php
function parseGuests(string $text): int
{
if (!ctype_digit($text)) {
throw new InvalidArgumentException("guests must be a number, got \"$text\"");
}
$guests = (int) $text;
if ($guests < 1 || $guests > 6) {
throw new InvalidArgumentException("guests must be between 1 and 6, got $guests");
}
return $guests;
}
try {
$guests = parseGuests($input);
} catch (InvalidArgumentException $e) {
echo "error: " . $e->getMessage();
}
PHP’s signature parseGuests(string $text): int does not say that it can fail; you learn it from the docs or from a crash. Go’s (int, error) says it in the signature, and the caller must take the error and decide.
The honest cost is repetition: if err != nil { return … } after every call that can fail. Go accepts it on purpose. The failure path is always visible, right next to the call, and there is no exception that skips three functions on its way up.
Go does have panic, which stops the program like an uncaught exception. It is for bugs that should never happen, never for bad input or a failed network call.
PracticeA Tour of Go: functions and if with a short statement, one small program
In A Tour of Go, do the basics pages Functions to Named return values, then If with a short statement and Exercise: Loops and Functions. Named return values are allowed in Go but this course does not use them: a plain return with no values hides what is returned.
Exercise: parse a number of nights
Write parseNights(text string) (int, error). It accepts a whole number from 1 to 28; anything else is an error whose message says what was wrong and what the input was. In main, call it for "3", "0", "30", "two" and "", and print either the nights or the error.
Show the solution
package main
import (
"fmt"
"strconv"
)
const maxNights = 28
func parseNights(text string) (int, error) {
nights, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("nights must be a whole number, got %q", text)
}
if nights < 1 || nights > maxNights {
return 0, fmt.Errorf("nights must be between 1 and %d, got %d", maxNights, nights)
}
return nights, nil
}
func report(input string) {
nights, err := parseNights(input)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Println("nights:", nights)
}
func main() {
report("3")
report("0")
report("30")
report("two")
report("")
}
nights: 3
error: nights must be between 1 and 28, got 0
error: nights must be between 1 and 28, got 30
error: nights must be a whole number, got "two"
error: nights must be a whole number, got ""Remember
- A function that can fail returns its error last; check it on the next line with
if err != nil, then return. - On failure return the zero value and the error; on success the value and
nil. - Never throw an error away with
_without a reason you could say out loud.
Tomorrow: slices and maps, the list and the lookup table, and range over both.