Go – Logical Operators

Logical operators are used to combine conditional statements and evaluate boolean expressions. These operators are essential for decision-making and controlling the flow of a program.

In this tutorial, we will explore the available logical operators in Go along with practical examples and detailed explanations.


List of Logical Operators

Go provides the following logical operators:

OperatorDescriptionExampleResult
&&Logical ANDa && btrue if both a and b are true
||Logical ORa || btrue if either a or b is true
!Logical NOT!atrue if a is false
Logical Operators

Examples of Logical Operators

Let’s explore how to use these logical operators in a Go program.


Example 1: Logical AND (&&)

The && operator returns true only if both conditions are true. Here’s an example:

</>
Copy
package main

import "fmt"

func main() {
    a := true
    b := false

    fmt.Println("a && b:", a && b) // false
    fmt.Println("true && true:", true && true) // true
}

Explanation

  1. Declare Variables: Two boolean variables a and b are initialized as true and false, respectively.
  2. Evaluate Logical AND: The expression a && b returns false because b is false.
  3. Print Results: The results of logical operations are printed using fmt.Println.

Output


Example 2: Logical OR (||)

The || operator returns true if at least one condition is true. Here’s an example:

</>
Copy
package main

import "fmt"

func main() {
    a := true
    b := false

    fmt.Println("a || b:", a || b) // true
    fmt.Println("false || false:", false || false) // false
}

Explanation

  1. Declare Variables: Two boolean variables a and b are initialized as true and false, respectively.
  2. Evaluate Logical OR: The expression a || b returns true because a is true.
  3. Print Results: The results of logical operations are printed using fmt.Println.

Output


Example 3: Logical NOT (!)

The ! operator reverses the boolean value. Here’s an example:

</>
Copy
package main

import "fmt"

func main() {
    a := true

    fmt.Println("!a:", !a) // false
    fmt.Println("!false:", !false) // true
}

Explanation

  1. Declare Variable: A boolean variable a is initialized as true.
  2. Evaluate Logical NOT: The expression !a returns false because a is true.
  3. Print Results: The result of the NOT operation is printed using fmt.Println.

Output


Key Notes for Logical Operators

  • The && operator evaluates to true only if both conditions are true.
  • The || operator evaluates to true if at least one condition is true.
  • The ! operator inverts the boolean value.
  • Logical operators are often used in if statements to control program flow.