In this tutorial, we will learn about the boolean data type in Go. We will cover the basics of defining and using boolean values, including how to perform logical operations and use booleans in control structures.
The bool
data type in Go represents boolean values, which can be either true
or false
. Booleans are commonly used in control structures and logical operations.
Boolean variables in Go can be defined using the var
keyword or by type inference.
var isActive bool = true
isClosed := false
Boolean values are often used in control structures such as if statements to determine the flow of a program.
if isActive {
fmt.Println("The system is active.")
} else {
fmt.Println("The system is inactive.")
}
Go supports standard logical operations such as AND, OR, and NOT on boolean values.
var a, b bool = true, false
fmt.Println(a && b) // AND operation
fmt.Println(a || b) // OR operation
fmt.Println(!a) // NOT operation
We can define and use boolean variables in Go to represent true or false values.
For example,
isActive
and assign it a value of true
.isClosed
using type inference and assign it a value of false
.package main
import "fmt"
func main() {
var isActive bool = true
isClosed := false
fmt.Println(isActive)
fmt.Println(isClosed)
}
true false
We can use boolean values in control structures such as if statements to determine the flow of a program.
For example,
isActive
and assign it a value.if-else
statement to print a message based on the value of isActive
.package main
import "fmt"
func main() {
isActive := true
if isActive {
fmt.Println("The system is active.")
} else {
fmt.Println("The system is inactive.")
}
}
The system is active.
We can perform standard logical operations such as AND, OR, and NOT on boolean values in Go.
For example,
a
and b
with values true
and false
, respectively.package main
import "fmt"
func main() {
var a, b bool = true, false
fmt.Println(a && b) // AND operation
fmt.Println(a || b) // OR operation
fmt.Println(!a) // NOT operation
}
false true false
We can combine multiple boolean expressions using logical operators to create complex conditions.
For example,
x
, y
, and z
with different values.package main
import "fmt"
func main() {
x := true
y := false
z := true
result := (x && y) || z
fmt.Println(result) // prints the result of the combined boolean expression
}
true