Golang Error Return Values in 5 Minutes
Go error return values for beginners in under five minutes, on a real Go program: why a function that can fail hands back a value and an error, what nil means, what the error type really is, why Go refuses an unused err but lets an underscore hide one, and how to return errors from your own functions with errors.New and fmt.Errorf.
Three drinks, two prices
Your Go program runs, prints a number, and the number is wrong, with no error anywhere. Dave runs a coffee cart. This morning he sold a latte, a mocha and a tea, and the loop that adds them up says: three drinks, seven hundred and fifty cents. The mocha is missing. So where did the error go? In under five minutes, you'll see where Go puts its errors, and how one character threw this one away.
sed -n '10,19p' main.goorders := []string{"latte 450", "mocha 4.75", "tea 300"} total := 0 for _, o := range orders { price := strings.Fields(o)[1] cents, _ := strconv.Atoi(price) total += cents } fmt.Println("Sold:", len(orders), "drinks") fmt.Println("Total:", total, "cents") }
go run .Sold: 3 drinks Total: 750 cents
Two values come back
In many languages, when something goes wrong, the program stops and shouts about it. Go doesn't do that. A function that can fail hands back two things: the result, and an error. Go has a function called Atoi, for ASCII to integer, that turns text into a whole number. Give it 450, and you get 450 back, plus nil. Nil is Go's word for nothing. So: no error. And what does it hand back for 4.75? Let's run it.

To catch both values, Dave puts two names before the colon-equals sign, n and err, and prints them side by side. For 450: 450, and nil. Guess first: for 4.75, what comes back? Zero, and an error: invalid syntax. In Dave's loop, the second name isn't err, it's an underscore, which throws the error away, so the zero went straight into his total. The same pattern shows up everywhere, like opening a file. Ask for a file that isn't there, and this time the first value, the file, is nil, meaning no file, and the error says it doesn't exist.
sed -n '10,15p' main.gon, err := strconv.Atoi("450") fmt.Println(n, err) n, err = strconv.Atoi("4.75") fmt.Println(n, err) f, err := os.Open("menu.txt") fmt.Println(f, err)
go run .450 <nil> 0 strconv.Atoi: parsing "4.75": invalid syntax <nil> open menu.txt: no such file or directory
Think of a dry cleaner. You get your coat back with a note pinned to it. A blank note means it's done. A note that says the stain wouldn't come out means the coat isn't what you asked for. So you read the note before you wear the coat. In Go, the error is that note.

What an error is
Dave's error printed as a line of text. So is an error just text? Let's ask Go itself: the go doc command prints Go's own documentation. An error is a small promise called an interface: anything that can describe itself as text, through a function named Error, counts as an error. And the doc's last line is the rule to remember: nil means no error.
go doc builtin.errorpackage builtin // import "builtin" type error interface { Error() string } The error built-in interface type is the conventional interface for representing an error condition, with the nil value representing no error.
Effective Go, the Go team's own guide, says the same thing: send back a detailed error next to the normal value. And by convention, that error has the type called error.

Could Dave just forget the error? Not by accident. If he changes the underscore to err and never uses it, Go won't even build: declared and not used. The underscore, called the blank identifier, is how you tell Go: throw this away, on purpose. That's why it's the one to watch for.
go run .# cart ./main.go:14:10: declared and not used: err
Read the error
So how should Dave's loop handle a bad price? He keeps the error, and reads it. The underscore becomes err. Now, if the error isn't nil, so something went wrong, he prints which order failed and why. Then the keyword continue jumps to the next order.

Now the run says it out loud: skipped, mocha 4.75, invalid syntax. The total is still 750, because the mocha is still left out. But now it's left out loudly, and Dave knows why: his helper Beth typed the mocha's price in dollars.
go run .skipped: mocha 4.75 - strconv.Atoi: parsing "4.75": invalid syntax Sold: 3 drinks Total: 750 cents
Return your own errors
But invalid syntax doesn't tell Beth what to fix. So Dave writes his own function, priceCents. Look at the end of its first line: int, error. That's how a function says it returns a whole number and an error, and the error always comes last. If an order has no price at all, it returns zero and errors.New, with a fixed message. If the price isn't whole cents, it uses fmt.Errorf, which puts the order itself into the message. And when the price is fine, it returns the price, and nil. Run it, and the mocha now says: price must be whole cents.
sed -n '10,21p' main.gofunc priceCents(order string) (int, error) { fields := strings.Fields(order) if len(fields) != 2 { return 0, errors.New("no price on the order") } cents, err := strconv.Atoi(fields[1]) if err != nil { return 0, fmt.Errorf("%q: price must be whole cents", order) } return cents, nil }
go run .problem: "mocha 4.75": price must be whole cents problem: no price on the order Total: 750 cents
Four habits to keep. Put the error last. nil means it worked. If the error isn't nil, don't trust the other value. And an underscore on an error should be a choice you can explain.

Recap
So: Dave's mocha went missing because one underscore swallowed its error. Read the error, like the note on your coat, before you trust the value.

If error values make sense now, a like helps YouTube show this to more beginners, and subscribing brings the next Go idiom: the if err not equal nil check.
Every command here ran for real, and the lab files are linked in the description. Thanks for watching Cloud Explainers.
Sources
- The Go Programming Language Specification: Return statements, The blank identifier, Errors (the predeclared error type), Implementation restriction on unused variables
- Package strconv, Atoi and NumError
- Package errors, New: https://pkg.go.dev/errors#New and package fmt, Errorf
- Effective Go: Multiple return values, and Errors
- The Go Blog, Errors are values
Demos: one container on our own Mac standing in for a laptop; the coffee cart is made up. Every command, error and number was real. Watch the full video on YouTube.