Multiple Return Values
Go functions can return more than one value - the canonical pattern is returning a result alongside an error.
Go functions can return more than one value. A common pair is (value, error). The error is nil when the operation worked; otherwise, callers check it before using the result.
List result types in parentheses and return nil, which means no error, when the operation succeeds. Use _ to ignore a result only when you do not need it.
package main
import (
"errors"
"fmt"
)
func divide(a, b float64) (float64, error) {
if b == 0 {
return 0, errors.New("division by zero")
}
return a / b, nil
}
func main() {
result, err := divide(10, 3)
if err != nil {
fmt.Println("error:", err)
return
}
fmt.Printf("%.2f\n", result)
}In production
Named results can make a short function easier to read. A bare return returns the named results without showing them on that line, so use explicit values in longer functions. Returning both a value and an error makes each caller handle failure before using the value.
Enjoyed this? Get more software craft delivered to your inbox.