How to Use Logical Operators in Go: Syntax and Examples
In Go, use
&& for logical AND, || for logical OR, and ! for logical NOT to combine or invert boolean expressions. These operators help control program flow by evaluating conditions in if statements or loops.Syntax
Go uses three main logical operators:
&&: Logical AND, true if both sides are true.||: Logical OR, true if at least one side is true.!: Logical NOT, inverts the boolean value.
They are used to combine or negate boolean expressions.
go
if condition1 && condition2 { // runs if both condition1 and condition2 are true } if condition1 || condition2 { // runs if either condition1 or condition2 is true } if !condition1 { // runs if condition1 is false }
Example
This example shows how to use logical operators to check multiple conditions in Go.
go
package main import "fmt" func main() { age := 20 hasID := true if age >= 18 && hasID { fmt.Println("Allowed to enter") } else { fmt.Println("Not allowed to enter") } isWeekend := false if !isWeekend { fmt.Println("Go to work") } isHoliday := false if isWeekend || isHoliday { fmt.Println("Day off") } else { fmt.Println("Work day") } }
Output
Allowed to enter
Go to work
Work day
Common Pitfalls
Common mistakes when using logical operators in Go include:
- Using a single
&or|instead of&&or||for logical operations (single ones are bitwise operators). - Forgetting to use parentheses to group conditions properly, which can cause unexpected results.
- Using logical operators on non-boolean types, which causes compile errors.
go
package main import "fmt" func main() { a := true b := false // Wrong: bitwise AND instead of logical AND // if a & b { // compile error: invalid operation // fmt.Println("This won't compile") // } // Correct: if a && b { fmt.Println("Both true") } else { fmt.Println("At least one is false") } // Grouping example: x := 5 y := 10 if (x > 0 && y > 0) || x == y { fmt.Println("Condition met") } }
Output
At least one is false
Condition met
Quick Reference
| Operator | Meaning | Example | Result |
|---|---|---|---|
| && | Logical AND | true && false | false |
| || | Logical OR | true || false | true |
| ! | Logical NOT | !true | false |
Key Takeaways
Use && for AND, || for OR, and ! for NOT to combine or invert boolean expressions in Go.
Always use double symbols (&&, ||) for logical operations, not single (&, |) which are bitwise.
Group complex conditions with parentheses to ensure correct evaluation order.
Logical operators only work with boolean values; mixing types causes errors.
Logical operators help control program flow by evaluating multiple conditions.