Welcome back to CodeYourCraft! Today, we're diving into the world of Go Logical Operators. These operators help us make complex decisions in our Go programs by combining simple conditions. Let's get started!
Logical operators in Go are used to combine simple conditions and form more complex ones. There are three logical operators: && (Logical AND), || (Logical OR), and ! (Logical NOT).
The && operator checks if both conditions are true. If both conditions are true, the entire expression evaluates to true; otherwise, it evaluates to false.
package main
import "fmt"
func main() {
x := 10
y := 20
if x < 10 && y > 20 {
fmt.Println("Both conditions are true")
}
}š” Pro Tip: The && operator has a short-circuit behavior. If the left operand is false, the right operand is not evaluated.
The || operator checks if at least one of the conditions is true. If at least one condition is true, the entire expression evaluates to true; otherwise, it evaluates to false.
package main
import "fmt"
func main() {
x := 10
y := 20
if x < 10 || y > 20 {
fmt.Println("At least one condition is true")
}
}The ! operator negates the logical value of its operand. If the operand is true, the entire expression evaluates to false, and if the operand is false, the entire expression evaluates to true.
package main
import "fmt"
func main() {
x := true
if !x {
fmt.Println("x is false")
}
}Operator precedence determines the order in which operators are evaluated. In Go, logical operators have lower precedence than relational and equality operators.
package main
import "fmt"
func main() {
x := 10
y := 20
if x < 10 && y > 20 {
fmt.Println("x is less than 10 and y is greater than 20")
} else if x < 10 || y < 10 {
fmt.Println("Either x is less than 10 or y is less than 10")
} else {
fmt.Println("None of the conditions are true")
}
}Now, it's time to test your knowledge!
Which of the following conditions is true for `x = 10` and `y = 20`?
What will be the output of the following code snippet?