Return Explicit Errors for Invalid Inputs in Go
Scenario
Compare Go’s (bool, error) return tuple on valid, boundary, and negative inputs.
func canBook(freeSeats int) (bool, error) {
if freeSeats < 0 {
return false, errors.New("INVALID_FREE_SEATS")
}
return freeSeats > 0, nil
}Try it yourself
Inspect both returned values for each input case.
| Case | Result |
|---|---|
| canBook(1) | Select a choice above to see what happens. |
| canBook(0) | Select a choice above to see what happens. |
| canBook(-1) | Select a choice above to see what happens. |
Reveal the explanation
- canBook(1)
Returns (true, nil) — nil error means success.
- canBook(0)
Returns (false, nil) — valid full room, no error.
- canBook(-1)
Returns (false, errors.New("INVALID_FREE_SEATS")) — caller checks err != nil.
Go’s static int type already rejects strings at compile time, while returning an error handles runtime domain violations like freeSeats < 0.
Download shared test cases
Your turn
Write the Go function signature and guard for didPassQuiz(score int) (bool, error) checking score < 0 || score > 100.
Common mistake Ignoring the returned err with _ in tests instead of checking err != nil.
Check your work
if score < 0 || score > 100 { return false, errors.New("INVALID_SCORE") }.
Quick check
This browser could not save your progress. Changes last until you leave the page.