Go Logical Operators šŸŽÆ

beginner
13 min

Go Logical Operators šŸŽÆ

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!

Understanding Logical Operators šŸ“

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).

Logical AND (&&) šŸ“

The && operator checks if both conditions are true. If both conditions are true, the entire expression evaluates to true; otherwise, it evaluates to false.

go
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.

Logical OR (||) šŸ“

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.

go
package main import "fmt" func main() { x := 10 y := 20 if x < 10 || y > 20 { fmt.Println("At least one condition is true") } }

Logical NOT (!) šŸ“

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.

go
package main import "fmt" func main() { x := true if !x { fmt.Println("x is false") } }

Operator Precedence šŸ“

Operator precedence determines the order in which operators are evaluated. In Go, logical operators have lower precedence than relational and equality operators.

go
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") } }

Practice Time šŸŽÆ

Now, it's time to test your knowledge!

Quick Quiz
Question 1 of 1

Which of the following conditions is true for `x = 10` and `y = 20`?

Quick Quiz
Question 1 of 1

What will be the output of the following code snippet?