Go Booleans
A boolean is a value that is either true or false. A comparison of two values makes a boolean.
A bool value prints
A bool variable holds true here. Printing the variable shows the word true.
package main
import "fmt"
func main() {
ready := true
fmt.Println(ready)
}Three comparisons
Each comparison makes a bool from two numbers. The prints show true first, then false twice.
package main
import "fmt"
func main() {
fmt.Println(7 >= 7)
fmt.Println(3 <= 2)
fmt.Println(5 != 5)
}Text compares by value
The == sign compares two strings by their text. Both sides hold the same text, so the result is true.
package main
import "fmt"
func main() {
fmt.Println("go" == "go")
}Joining and flipping
&& needs both sides true, so the first print gives false. || needs one side true, and ! flips true to false.
package main
import "fmt"
func main() {
fmt.Println(true && false)
fmt.Println(false || true)
fmt.Println(!true)
}Example
package main
import "fmt"
func main() {
age := 20
member := false
fmt.Println("Adult:", age >= 18)
fmt.Println("Member price:", age >= 18 && member)
}Key points
- The bool type holds true or false.
- Use == to test whether two values are equal.
- Use != to test whether two values differ.
- The sign >= tests greater than or equal, and <= tests less than or equal.
- && needs both sides true, and || needs one side true.
- ! flips a boolean, turning true into false and false into true.
In this example, age holds 20 and member holds false. The test age >= 18 gives true, so the first line prints Adult: true. The joined test also needs member, so the second line prints Member price: false.
Note
A comparison makes its bool at once. A program can print the bool or store it in a variable.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Go Playground
Exercise
What does 5 != 5 print?