0
0
Goprogramming~5 mins

Logical operators in Go

Choose your learning style9 modes available
Introduction

Logical operators help you combine or change true/false values to make decisions in your program.

Checking if two conditions are both true before running some code.
Running code if at least one of several conditions is true.
Making sure a condition is not true before continuing.
Combining multiple checks to control program flow clearly.
Syntax
Go
condition1 && condition2  // AND: true if both are true
condition1 || condition2  // OR: true if at least one is true
!condition               // NOT: true if condition is false

Use && for AND, || for OR, and ! for NOT.

Logical operators work with boolean values: true or false.

Examples
AND returns true only if both a and b are true.
Go
a := true
b := false
result := a && b  // result is false
OR returns true if either a or b is true.
Go
a := true
b := false
result := a || b  // result is true
NOT flips the value: true becomes false, false becomes true.
Go
a := true
result := !a  // result is false
Sample Program

This program shows how to use AND, OR, and NOT operators with boolean values. It also uses them in an if statement to check conditions.

Go
package main

import "fmt"

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

    fmt.Println("a AND b:", a && b)  // false
    fmt.Println("a OR b:", a || b)   // true
    fmt.Println("NOT a:", !a)        // false

    // Using logical operators in if
    if a && !b {
        fmt.Println("a is true and b is false")
    }
}
OutputSuccess
Important Notes

Logical operators short-circuit: in a && b, if a is false, b is not checked.

Use parentheses () to group conditions clearly when combining multiple logical operators.

Summary

Logical operators combine true/false values to control decisions.

&& means AND, || means OR, and ! means NOT.

They help write clear and simple conditions in your programs.