0% completed
Booleans in Go
On This Page
What is a Boolean?
Declaring and Initializing Boolean Variables
Syntax
Example: Using Boolean Variables
Default Value of a Boolean Variable
Example
Booleans are one of the simplest but most important data types in programming. They are used for decision-making, logical operations, and flow control in a program. In this lesson, we will explore the Boolean data type in Go, including its syntax, examples, and use cases.
What is a Boolean?
A Boolean is a data type that can hold only two values:
true→ Represents a logical truth.false→ Represents a logical falsehood.
Booleans are mainly used in conditional statements, such as if-else blocks and loops.
Go provides a built-in Boolean type:
| Data Type | Description |
|---|---|
bool | Can store true or false values |
By default, an uninitialized Boolean variable in Go is set to false.
Declaring and Initializing Boolean Variables
Syntax
var variableName bool = value
var→ Keyword to declare a variable.variableName→ Name of the variable.bool→ Specifies the Boolean data type.value→ Can be eithertrueorfalse.
You can also use type inference, where Go automatically detects the Boolean type:
var isReady = true
Example: Using Boolean Variables
Explanation
isAvailableis explicitly declared as abooland assignedtrue.isLoggedInis declared without specifying a type. Since it holdsfalse, Go infers that it is abool.- The values are printed using
fmt.Println().
Default Value of a Boolean Variable
If you declare a Boolean variable without assigning a value, it gets the default value of false.
Example
Explanation
Since isValid is not initialized, it takes the default value false.
In the next lesson, we will explore Strings in Go, how they work, and the different ways to manipulate them.
Reading Progress
0%
On This Page
What is a Boolean?
Declaring and Initializing Boolean Variables
Syntax
Example: Using Boolean Variables
Default Value of a Boolean Variable
Example