Home »
Golang
Go Boolean Data Type
Last Updated : May 18, 2025
In Go, the boolean data type is used to represent truth values: true
or false
. It is commonly used in conditional logic and decision-making.
Declaring Boolean Variables with Explicit Data Type
You can declare a boolean variable using the var
keyword and explicitly specify the bool
data type:
var isActive bool = true
var isEnabled bool = false
Example
In this example, we declare boolean variables with explicit types and print their values:
package main
import "fmt"
func main() {
var isActive bool = true
var isEnabled bool = false
fmt.Println("Active:", isActive)
fmt.Println("Enabled:", isEnabled)
}
When executed, this program outputs:
Active: true
Enabled: false
Shorthand Declaration of Boolean Variable
You can also declare boolean variables using shorthand syntax without specifying the data type explicitly:
isMember := true
isGuest := false
Example
This example shows how to use shorthand declaration for boolean variables:
package main
import "fmt"
func main() {
isMember := true
isGuest := false
fmt.Println("Member:", isMember)
fmt.Println("Guest:", isGuest)
}
When executed, this program outputs:
Member: true
Guest: false
Default Boolean Value
If a boolean variable is declared without initialization, it defaults to false
.
Example
package main
import "fmt"
func main() {
var status bool
fmt.Println("Default status:", status)
}
When executed, this program outputs:
Default status: false
Using Booleans in Conditional Statements
Boolean variables and expressions are used in if
conditions.
Example
This example decides whether someone can vote based on their age:
package main
import "fmt"
func main() {
age := 20
isEligible := age >= 18
if isEligible {
fmt.Println("You are eligible to vote.")
} else {
fmt.Println("You are not eligible to vote.")
}
}
When executed, this program outputs:
You are eligible to vote.
Logical Operators for Boolean Expressions
Go supports common logical operators for boolean expressions:
Example
This example demonstrates basic boolean operations such as AND (&&
), OR (||
), and NOT (!
) in Go:
package main
import "fmt"
func main() {
a := true
b := false
fmt.Println("a && b:", a && b)
fmt.Println("a || b:", a || b)
fmt.Println("!a:", !a)
}
When executed, this program outputs:
a && b: false
a || b: true
!a: false
Boolean Data Type Exercise
Select the correct option to complete each statement about the boolean data type in Go.
- The zero value of a boolean in Go is ___.
- Which of the following is a valid boolean expression?
- What does
!true
evaluate to?
Advertisement
Advertisement