Curriculum

Curriculum

Return Explicit Errors for Invalid Inputs in Go

Scenario

Compare Go’s (bool, error) return tuple on valid, boundary, and negative inputs.

Selected choicePick a choice below
Result—
Go
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.

Reveal the explanation
  1. canBook(1)

    Returns (true, nil) — nil error means success.

  2. canBook(0)

    Returns (false, nil) — valid full room, no error.

  3. 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.

Review first
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

In Go, what does a returned err == nil signify?
Show the answer and reasoning

Correct answer The input was valid and the function completed without error

In Go, nil error indicates success; a non-nil error signals an invalid input or failure.