Design guard conditions
Design guard conditions
A guard condition checks whether it is safe or meaningful to proceed before a risky operation. In this lesson use an if/else or an early return from main: return ends main and therefore the program in these examples. Combine Boolean comparisons with && and || to express valid ranges and reject bad input.
package main
import "fmt"
func main() { total, count := 20, 0 if count == 0 { fmt.Println("no items") } else { fmt.Println(total / count) }}The zero check prevents integer division by zero. The else branch is evaluated only if count is nonzero. A positive-count guard would be more appropriate when the application contract also excludes negative item counts.
Reject invalid input early
package main
import "fmt"
func main() { total, count := 20, 4 if count <= 0 || total < 0 { fmt.Println("invalid input") return } if count != 0 && total/count >= 5 { fmt.Println("at least five per item") }}The first guard rejects nonpositive counts and negative totals. Early return keeps the main path less nested. In the next condition, && evaluates its right operand only if the left is true; this is short-circuit evaluation. Here the nonzero check is redundant after the first guard, but illustrates why checking a divisor before dividing matters. Reversing the operands could panic in an unguarded context. Use || to reject a value outside a range, not &&.
Try it locally
For score := 105, reject values outside 0 through 100 using ||, print invalid and return. Otherwise print accepted. Expected: invalid. Repeat with 0 and 100 to check the inclusive boundaries.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Branching 06: Design guard conditions
Check the lesson objective before moving on.
Which guard rejects all scores outside 0 through 100?
Which condition avoids division by zero when count is zero?