In Go we have three logical operators - && (logical and), || (logical or) and ! (negation).
Go Boolean operators
Boolean operators are also called logical.
Many expressions result in a boolean value. For instance, boolean values are used in conditional statements.
package main
import "fmt"
func main() {
var x = 3
var y = 5
fmt.Println(x == y)
fmt.Println(y > x)
if y > x {
fmt.Println("y is greater than x")
}
}
Output:
false true y is greater than x
Go Logical and (&&) operator
The code example shows the logical and (&&) operator. It evaluates to true only if both operands are true.
package main
import "fmt"
func main() {
var a = true && true
var b = true && false
var c = false && true
var d = false && false
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Output:
true false false false
Go Logical or (||) operator
The logical or (||) operator evaluates to true if either of the operands is true.
package main
import "fmt"
func main() {
var a = true || true
var b = true || false
var c = false || true
var d = false || false
fmt.Println(a)
fmt.Println(b)
fmt.Println(c)
fmt.Println(d)
}
Output:
true true true false
Go negation operator !
The negation operator ! makes true false and false true.
package main
import "fmt"
func main() {
fmt.Println(!true)
fmt.Println(!false)
}
Output:
false true true