Logical operators in Go are used to evaluate the relationship between variables or values by determining the truth of logical conditions. They are essential for decision-making in programming.
List of Logical Operators in Go
Here is a breakdown of the logical operators, their purpose, and examples:
Operator | Name | Description | Example |
---|---|---|---|
&& | Logical AND | Returns true only if both conditions are true . | x < 5 && x < 10 |
|| | Logical OR | Returns true if at least one condition is true . | x < 5 || x < 4 |
! | Logical NOT | Reverses the result; returns true if the condition is false . | !(x < 5 && x < 10) |
Examples Using Logical Operators
Here is a practical demonstration of how logical operators can be used in a Go program. To make it interesting, we’ll incorporate motorcycle brands:
Go
x
package main
import "fmt"
func main() {
ducati := 7
yamaha := 9
// Logical AND
fmt.Println(ducati < 10 && yamaha < 10) // true, both conditions are true
// Logical OR
fmt.Println(ducati > 8 || yamaha > 8) // true, one condition is true
// Logical NOT
fmt.Println(!(ducati < 10 && yamaha < 10)) // false, reversing the result of true
}
Explanation of Examples
- Logical AND (
&&
):- Both
ducati
andyamaha
are compared to check if they are less than 10. - The output is
true
because both conditions evaluate totrue
.
- Both
- Logical OR (
||
):- Checks if either
ducati
is greater than 8 oryamaha
is greater than 8. - The output is
true
because at least one condition (yamaha > 8) istrue
.
- Checks if either
- Logical NOT (
!
):- Negates the result of
(ducati < 10 && yamaha < 10)
, which is originallytrue
. - The output becomes
false
.
- Negates the result of