Logical Operators
Logical Operators
Sometimes one condition isn't enough. You need to check if someone is old enough AND has a ticket, or if they're an admin OR the owner.
Go gives you three logical operators to combine conditions:
| Operator | Meaning | Example |
|---|---|---|
&& |
and, both must be true | age >= 18 && hasTicket |
|| |
or, at least one true | isAdmin || isOwner |
! |
not, flips a boolean | !ready |
if age >= 18 && hasID {
fmt.Println("Welcome")
}
if isAdmin || isOwner || isModerator {
fmt.Println("Access granted")
}
if !maintenance {
fmt.Println("System is up")
}You can combine multiple operators in one expression. Use parentheses to make the grouping clear:
if (age >= 18 && hasTicket) || isVIP {
fmt.Println("You're in")
}Without parentheses, && binds tighter than || (just like * before + in math). But when in doubt, add parentheses to make your intent obvious.
Go also short-circuits: if the left side of && is false, it skips the right side entirely. If the left side of || is true, it skips the right side. This matters when the right side has a function call you might not want to run.
Booleans are already booleans
If you have a bool variable, you don't need to compare it to true:
if cpuHigh == true { ... } // works, but verbose
if cpuHigh { ... } // same thing, idiomatic
if !cpuHigh { ... } // checks for false
Extra == true checks are more typing and more places to typo a variable name. Just use the bool directly.
Mapping conditions to outcomes
When a rule depends on several bools, it helps to lay out every combination. For the exercise below, three inputs (cpuHigh, memoryHigh, diskFull) mean 2 × 2 × 2 = 8 cases, and the rules collapse them into three outcomes:
cpuHigh |
memoryHigh |
diskFull |
result |
|---|---|---|---|
| true | true | any | CRITICAL |
| true | false | any | WARNING |
| false | true | any | WARNING |
| false | false | true | WARNING |
| false | false | false | OK |
A "match any row" structure like this maps directly onto if / else if / else.
Exercise: System Monitor
You're building a server monitoring alert system. Update the status variable inside checkSystem based on these rules:
If both cpuHigh and memoryHigh are true, set status to "CRITICAL".
If at least one of cpuHigh, memoryHigh, or diskFull is true, set status to "WARNING".
Check for "CRITICAL" before "WARNING", since a critical situation also matches the warning condition.
If nothing is wrong, status stays "OK" (the default).
Examples:
checkSystem(true, true, false)→"CRITICAL"(CPU and memory both high)checkSystem(true, false, false)→"WARNING"(only CPU is high)checkSystem(false, false, false)→"OK"(nothing is wrong)