Boolean in Golang is used to represent true or false. Booleans are used to make decisions in your program for example if a feature is enabled or not

Declare Boolean variable

You can use the bool keyword of Golang to declare a boolean variable. The default value of a boolean variable will be false

package main

import "fmt"

func main() {
 // decalare a boolean variable
	var x bool
	fmt.Println(x)
}
Bash
  hello-world go run main.go
false

Initialize a Boolean variable

You can assign only two values to a boolean variable

  • true
  • false

Let’s assign a true value and print it

package main

import "fmt"

func main() {
	// declare and initialize a boolean variable
	var x bool = true
	fmt.Println(x)
}
Bash
  hello-world go run main.go
true

Declare and initialize a false value to a boolean variable and print it

package main

import "fmt"

func main() {
	// declare and initialize a boolean variable
	var x bool = false
	fmt.Println(x)
}
Bash
  hello-world go run main.go
false

References

Leave a Reply

Your email address will not be published. Required fields are marked *