Combine boolean conditions
Combine boolean conditions
Use && when both conditions must be true, || when at least one must be true, and ! to reverse a boolean. Go requires boolean operands; an integer such as 1 is not a truth value.
package main
import "fmt"
func main() { paid := true inStock := false fmt.Println(paid && inStock) fmt.Println(paid || inStock, !inStock)}The order cannot ship because the item is out of stock. At least one condition is true, so OR is true. NOT changes false to true.
Short-circuit evaluation
package main
import "fmt"
func main() { count := 0 total := 20 fmt.Println(count != 0 && total/count > 2) fmt.Println(count == 0 || total/count > 2)}Go evaluates the right operand only if necessary. With && a false left operand skips the right; with || a true left operand skips it. Here neither division runs, avoiding integer division by zero. Put the safety check before the operation it protects.
Try it locally
Use age = 19 and hasTicket = true. Print whether age is at least 18 and a ticket is present, and whether either requirement is missing. Expected: true false.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Expressions and Arithmetic 03: Combine boolean conditions
Check the lesson objective before moving on.
When does && skip its right operand?
Which expression is true if at least one condition is true?