On Day 5 you called functions that can fail, such as strconv.Atoi. Today you write them. Moving a rule such as "minutes must be from 1 to 240" into a function gives it a name, puts it in one place, and lets every part of the program use the same version of it. Your own function can return a value and an error together. Return nil as the error when the value is valid. For an invalid value, return errors.New with a message that explains the rule. The caller decides how to show it.
The result list (int, error) goes in parentheses because there is more than one result. Every return in the function must then supply exactly two values, in that order. By convention the error comes last.
Predict and run
What does the caller see for zero?
package main
import (
"errors"
"fmt"
)
func validate(minutes int) (int, error) {
if minutes <= 0 {
return 0, errors.New("duration must be positive")
}
return minutes, nil
}
func main() {
minutes, err := validate(0)
if err != nil {
fmt.Println(err)
} else {
fmt.Println(minutes)
}
}Check your prediction
duration must be positiveTry validate(1) and predict which branch runs.
What to return when something fails
On a failure path the function must still return a value of the first type. The convention is to return that type's zero value, such as 0, "" or an empty struct, and the caller agrees not to use it whenever the error is not nil. On the success path, return the real value and nil. Keeping to this pattern means a caller never has to guess which of the two results is meaningful.
Writing a useful error message
errors.New makes an error from a fixed message. When the message should include a value, use fmt.Errorf, which takes a format string just like Printf and returns an error instead of printing. Go error messages conventionally start with a lower-case letter and have no final period, because they are often combined into longer messages, such as line 4: minutes must be from 1 to 240.
package main
import (
"fmt"
)
func validate(minutes int) (int, error) {
if minutes < 1 || minutes > 240 {
return 0, fmt.Errorf("%d is outside 1 to 240 minutes", minutes)
}
return minutes, nil
}
func main() {
for _, minutes := range []int{30, 300} {
accepted, err := validate(minutes)
if err != nil {
fmt.Println("Rejected:", err)
continue
}
fmt.Println("Accepted:", accepted)
}
}Accepted: 30
Rejected: 300 is outside 1 to 240 minutesA function that parses a whole line
The real payoff comes when a function combines several checks. The function below takes one input line and returns a Session or the first problem it finds. main no longer knows anything about commas, trimming or ranges; it just asks for a session and reports the error if there is one. That is very close to how the reading log on Day 7 is built.
package main
import (
"errors"
"fmt"
"strconv"
"strings"
)
type Session struct {
Title string
Minutes int
}
func parse(line string) (Session, error) {
title, raw, found := strings.Cut(line, ",")
if !found {
return Session{}, errors.New("use title,minutes")
}
title = strings.TrimSpace(title)
if title == "" {
return Session{}, errors.New("title is required")
}
minutes, err := strconv.Atoi(strings.TrimSpace(raw))
if err != nil || minutes < 1 || minutes > 240 {
return Session{}, errors.New("use 1–240 whole minutes")
}
return Session{Title: title, Minutes: minutes}, nil
}
func main() {
for _, line := range []string{"Poems, 25", "Poems", " ,20", "Essays,later"} {
s, err := parse(line)
if err != nil {
fmt.Printf("%q: %v\n", line, err)
continue
}
fmt.Printf("%s: %d min\n", s.Title, s.Minutes)
}
}Poems: 25 min
"Poems": use title,minutes
" ,20": title is required
"Essays,later": use 1–240 whole minutesEach early return handles one problem and leaves the function. The line that builds the Session is reached only when every check has passed, so a caller can trust any session it receives without an error.
An error or a bool?
Some functions return (int, bool) instead, such as the map lookup's comma-ok form. A bool is enough when there is only one way to fail and the caller does not need to explain it. Return an error when there are several reasons, or when the message should reach the person using the program.
Practice
Your turn
Write parseMinutes, which takes the text someone typed and returns (int, error). Text that is not a whole number gets an error saying so. A number outside 1 to 240 gets an error that names the number. The starter's main already calls it for four inputs, so it prints this once your function is written:
Accepted: 45
Rejected: "abc" is not a whole number
Rejected: 0 is outside 1 to 240 minutes
Rejected: 300 is outside 1 to 240 minutespackage main
import (
"fmt"
)
func parseMinutes(text string) (int, error) {
// Replace this line with your checks.
return 0, nil
}
func main() {
for _, text := range []string{"45", "abc", "0", "300"} {
minutes, err := parseMinutes(text)
if err != nil {
fmt.Println("Rejected:", err)
continue
}
fmt.Println("Accepted:", minutes)
}
}Hint 1: the idea
The function has two ways to fail, so it has two early returns, each with the zero value and its own error. Only a value that gets past both checks reaches the final return with nil.
Hint 2: a first step
Call strconv.Atoi(text) first. When its error is not nil, return 0 and an error built with fmt.Errorf and the %q verb. Run it: abc should now be rejected, while 0 and 300 are still accepted.
Worked solution
package main
import (
"fmt"
"strconv"
)
func parseMinutes(text string) (int, error) {
minutes, err := strconv.Atoi(text)
if err != nil {
return 0, fmt.Errorf("%q is not a whole number", text)
}
if minutes < 1 || minutes > 240 {
return 0, fmt.Errorf("%d is outside 1 to 240 minutes", minutes)
}
return minutes, nil
}
func main() {
for _, text := range []string{"45", "abc", "0", "300"} {
minutes, err := parseMinutes(text)
if err != nil {
fmt.Println("Rejected:", err)
continue
}
fmt.Println("Accepted:", minutes)
}
}Accepted: 45
Rejected: "abc" is not a whole number
Rejected: 0 is outside 1 to 240 minutes
Rejected: 300 is outside 1 to 240 minutesThe conversion is checked before the range, because minutes means nothing when Atoi failed. Each message starts in lower case and has no final period, so main can put Rejected: in front of it. main didn't change at all: the rules live in one function.
Completion is saved in this browser only. It does not measure mastery.