Selected Reading

Go - Logical Operators



The following table shows all the logical operators supported by Go language. Assume variable A holds true and variable B holds false, then −

Operator Description Example
&& Called Logical AND operator. If both the operands are false, then the condition becomes false. (A && B) is false.
|| Called Logical OR Operator. If any of the two operands is true, then the condition becomes true. (A || B) is true.
! Called Logical NOT Operator. Use to reverses the logical state of its operand. If a condition is true, then Logical NOT operator will make it false. !(A && B) is true.

Example - Usage of Logical AND Operator

Try the following example to understand AND operator available in Go programming language −

main.go

package main

import "fmt"

func main() {
   var a bool = true
   var b bool = false   
 
   if ( a && b ) {
      fmt.Printf("a && b is true\n" )
   }else {
      fmt.Printf("a && b is false\n" )   
   }
   
   /* lets change the value of  a and b */
   a = false
   b = true 
   
   if ( a && b ) {
      fmt.Printf("a && b is true\n" )
   }else {
      fmt.Printf("a && b is false\n" )   
   }
}

Output

When you compile and execute the above program it produces the following result −

a && b is false
a && b is false

Example - Usage of Logical OR Operator

Try the following example to understand OR operator available in Go programming language −

main.go

package main

import "fmt"

func main() {
   var a bool = true
   var b bool = false   
 
   if ( a || b ) {
      fmt.Printf("a || b is true\n" )
   }else {
      fmt.Printf("a || b is false\n" )   
   }
   
   /* lets change the value of  a and b */
   a = false
   b = true 
   
   if ( a || b ) {
      fmt.Printf("a || b is true\n" )
   }else {
      fmt.Printf("a || b is false\n" )   
   }
}

Output

When you compile and execute the above program it produces the following result −

a || b is true
a || b is true

Example - Usage of Logical NOT Operator

Try the following example to understand NOT operator available in Go programming language −

main.go

package main

import "fmt"

func main() {
   var a bool = true
 
   if (!a ) {
      fmt.Printf("a is false\n" )
   }else {
      fmt.Printf("a is true\n" )   
   }
   
   /* lets change the value of  a */
   a = false
   
   if (!a ) {
      fmt.Printf("a is false\n" )
   }else {
      fmt.Printf("a is true\n" )   
   }
}

Output

When you compile and execute the above program it produces the following result −

a is true
a is false
Advertisements