×

go · level 2 · unit 4 · lesson 1

  1. meet it
  2. guess first
  3. your turn
  4. fix it
  5. nailed it

Tap a green word if you get lost.

meet it

Your own functions can hand back errors too.

Your functions can fail as well. Say the cinema sells at most 10 tickets per order. A buy function can return two results, (int, error): the price when all is well, or an error saying what went wrong.

makes an error value with a fixed message. works like Sprintf and builds an error from placeholders: fmt.Errorf("%v is too many", tickets).

Check the bad cases first and , handing back the zero value with the error: return 0, err. At the end, once every check has passed, return the real answer and nil.

package main
import "errors"
import "fmt"
func buy(tickets int) (int, error) {
	if tickets < 1 {
		return 0, errors.New("buy at least one ticket")
	}
	if tickets > 10 {
		return 0, fmt.Errorf("%v is too many, the limit is 10", tickets)
	}
	return tickets * 4, nil
}
func main() {
	for _, n := range []int{2, 0, 12} {
		price, err := buy(n)
		fmt.Println(price, err)
	}
}

Error messages start with a small letter and end without a full stop, because they often get joined onto other text.