An exciting lesson awaits us, promising a deeper exploration of Go's variables and Boolean types. In earlier lessons, we covered the basics of Go, and now we're going to build on that by exploring how to use Boolean variables. These are simple yet powerful, used to represent a condition or status as either true
or false
.
In this lesson, we'll define two string variables: each will hold the name of a destination. We'll also explore how to use Boolean variables — a type of variable that can only be true
or false
, similar to a light switch that can only be either on (true
) or off (false
). Here's what it looks like in Go:
Go1package main 2 3import ( 4 "fmt" 5) 6 7func main() { 8 destinationA := "Paris" 9 destinationB := "Tokyo" 10 11 hasVisitedA := true 12 hasVisitedB := false 13 14 fmt.Println(destinationA, "visited:", hasVisitedA) 15 fmt.Println(destinationB, "visited:", hasVisitedB) 16}
Here, destinationA
and destinationB
store strings representing travel destinations. On the other hand, hasVisitedA
and hasVisitedB
are Boolean variables that, like an on-off switch, inform us whether these destinations have been visited.
In Go, Boolean values can be derived from various expressions using comparison operators. These operators compare values and return a Boolean result (true
or false
). Common comparison operators include:
==
for equality!=
for inequality<
for less than<=
for less than or equal to>
for greater than>=
for greater than or equal to
Here's how you can use these operators in Go:
Go1package main 2 3import ( 4 "fmt" 5) 6 7func main() { 8 // Comparing numbers 9 a := 5 10 b := 10 11 12 isEqual := a == b 13 isNotEqual := a != b 14 isLessThan := a < b 15 isGreaterThan := a > b 16 17 fmt.Println("Is equal:", isEqual) // false 18 fmt.Println("Is not equal:", isNotEqual) // true 19 fmt.Println("Is less than:", isLessThan) // true 20 fmt.Println("Is greater than:", isGreaterThan) // false 21 22 // Comparing strings 23 name1 := "Alice" 24 name2 := "Bob" 25 26 areNamesEqual := name1 == name2 27 28 fmt.Println("Are names equal:", areNamesEqual) // false 29}
These expressions are essential for making decisions in programming, enabling you to direct the flow of your program based on conditions.
Understanding variables in Go is an essential skill for any programmer. They enable us to store, retrieve, and manipulate values within our code efficiently. Booleans, meanwhile, allow us to control program flow and make decisions based on conditions. Together, variables and booleans form a powerful foundation for writing dynamic and flexible programs.
Well done on reaching this stage in your Go journey! Everyone here on the course team is proud of your progress and can't wait to see what you achieve next.
Onward to our practice exercises!