Introduction to Go Variables and Booleans

Introduction to Go Variables and Booleans

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.

What You'll Learn

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:

package main

import (
    "fmt"
)

func main() {
    destinationA := "Paris"
    destinationB := "Tokyo"
    
    hasVisitedA := true
    hasVisitedB := false

    fmt.Println(destinationA, "visited:", hasVisitedA)
    fmt.Println(destinationB, "visited:", hasVisitedB)
}

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.

Getting Boolean Values from Expressions

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:

package main

import (
    "fmt"
)

func main() {
    // Comparing numbers
    a := 5
    b := 10
    
    isEqual := a == b
    isNotEqual := a != b
    isLessThan := a < b
    isGreaterThan := a > b
    
    fmt.Println("Is equal:", isEqual)              // false
    fmt.Println("Is not equal:", isNotEqual)       // true
    fmt.Println("Is less than:", isLessThan)       // true
    fmt.Println("Is greater than:", isGreaterThan) // false

    // Comparing strings
    name1 := "Alice"
    name2 := "Bob"

    areNamesEqual := name1 == name2
    
    fmt.Println("Are names equal:", areNamesEqual) // false
}

These expressions are essential for making decisions in programming, enabling you to direct the flow of your program based on conditions.

Sign up

Join the 1M+ learners on CodeSignal

Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal