Grokking Go
Vote

0% completed

​

Booleans in Go

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 TypeDescription
boolCan 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 either true or false.

You can also use type inference, where Go automatically detects the Boolean type:

var isReady = true

Example: Using Boolean Variables

Go
Go

. . . .

Explanation

  • isAvailable is explicitly declared as a bool and assigned true.
  • isLoggedIn is declared without specifying a type. Since it holds false, Go infers that it is a bool.
  • 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

Go
Go

. . . .

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%


Vote for new content

On This Page

What is a Boolean?

Declaring and Initializing Boolean Variables

Syntax

Example: Using Boolean Variables

Default Value of a Boolean Variable

Example