Results and errors side by side
A function calmly returns several values. The error is the last of them, not an exception.
A function returns as many values as you need. The accepted order is the useful result, then error.
func ReadUser(id int) (User, error) {
return User{}, nil
}
The caller cannot honestly ignore the error without writing _. That is the design: the error is visible in the signature. An empty return is possible only when the results are named:
func parse(s string) (n int, err error) {
if s == "" {
err = errors.New("empty")
return
}
return
}
A naked return returns whatever currently sits in the names. It is short in a long function, and dangerous for the same reason: it is unclear which value will leave. In new code a naked return belongs in short functions, where the names are the meaning.
A variadic parameter is last and has a slice type:
func Sum(nums ...int) int {
total := 0
for _, n := range nums {
total += n
}
return total
}
Inside the function nums is an ordinary []int. You can pass nothing at all, and then the slice is nil.
Do not return everything in a row
Three or four results are a signal that it is time for a struct. (user, token, expires, error) is worse than (Session, error). Named results are useful when the name makes the contract clear (n int, err error). They are not needed so that it "looks like the tutorial".
Practice
Where the error goes
How does the standard library usually shape the signature of a function that can fail?
- Throw a panic and catch it in main
- Return the result and error as the last value
- Write the error into a global errno variable
- Return only a bool
Repeating a string
Write
Repeat(s string, n int) string. Whenn > 0, returnsrepeatedntimes. Whenn <= 0, return an empty string.A naked return
When does a
returnwith no values compile at all?- Always, if the function is one line
- Only when the results are named
- Only in main
- Only if the function returns nothing