Golang_tutorial_zero_to_hero

Conditionals

Conditionals are used to control the flow of data points through your program. They are used to introduce logical paths that are used to navigate functions.

Boolean Operators

Boolean operators are used for evaluating statements that result in Boolean conditions. Operators include &&(and), ||(or), >(greater than), >=(greater than or equal to), < (less than), <=(less than or equal to), !=(does not equal), ! (not), and ==(equal to).

Now would be a good time for us to experiment with these operators. In your browser, navigate to your favorite Go text editor Go Playspace. Let’s start by evaluating some statements. We will start with something that we know is true. In your file, change your main function to resemble the following:

func main() {
	fmt.Println(1 < 2)
}

When you run this code you should see the Boolean value printed of true or false. Since 2 is in fact a larger number than 1, we expect the statement 1 < 2 to be evaluated as true. If that is printed below, we win!

Now let us try to anticipate the result. Copy and paste the following into your Playspace replacing your main function. Replace the underlined portion with your guess of what you think the Boolean statement will evaluate to.

func main() {
	fmt.Printf("the statement 2 >= 3 is %v I guess _____ \n", 2 >= 3)
	fmt.Printf("the statement 2 < 3 is %v I guess _____ \n", 2 >= 3)
	fmt.Printf("the statement 2 == 3 is %v I guess _____ \n", 2 >= 3)
	fmt.Printf("the statement 2 != 3 is %v I guess _____ \n", 2 >= 3)
}

And just for funzies, we will try one more set of guessercises. These will be a little more complicated. Feel free to put these into your Playspace and guess the result.

func main() {
	fmt.Println(true && false)
	fmt.Println(true && true)
	fmt.Println(false && false)
	fmt.Println(false && true)

	fmt.Println(true || false)
	fmt.Println(true || true)
	fmt.Println(false || false)
	fmt.Println(false || true)
}

Here we used the && operator. This Boolean statement will only return true if the conditions on BOTH sides of the operator are met. The other operator we used, ||, returns true when EITHER condition on each side of the operator is met.

Control Flow

Sometimes when we are writing new code, we have to use Boolean conditions and logic to define certain behaviors. This is called Control Flow. It is essential that we use these conditions to control when certain bits of code are run.

Here is an example from the Go Standard Library. There may be some syntaxes in this example that we have not covered yet, so it’s ok if it doesn’t all make sense. However, by the end of this section you should be able to read through the example code and understand the conditions that have to be met for the code to be executed.

func (s *ss) Token(skipSpace bool, f func(rune) bool) (tok []byte, err error) {
	defer func() {
		if e := recover(); e != nil {
			if se, ok := e.(scanError); ok {
				err = se.err
			} else {
				panic(e)
			}
		}
	}()
	if f == nil {
		f = notSpace
	}
	s.buf = s.buf[:0]
	tok = s.token(skipSpace, f)
	return
}

If statements

My personal opinion is that the if statement is the most powerful conditional statement in the Go programming language. It is used everywhere. Take a look at this snippet from the Go Sandard Library Just take a quick second to count how many if statements there are on the page - they really are used everywhere.

If statements take a Boolean condition and run the code contained by the if statement only when the condition is met. Let’s explore this in code!

Problem:

Your local movie theater is having a special viewing of Pulp Fiction to help encourage movie theater attendance in a post COVID-19 world. The movie theater has an age restriction on who can purchase tickets. We need to write a function that tells us if customer is old enough to purchase a ticket.

In your main function, start by defining a variable called age. Set the age variable to any number. Now, let’s define the if statement. Below your age, paste the following:

if age >= 17 {
fmt.Println("You are allowed to buy a ticket")
}

If the age condition is met, you should see the sentence printed out when you run the code. If the condition isn’t met, nothing will be printed.

Else Statements

An else statement is used to define a certain type of flow. It follows your typical if -> then scenarios. If the condition of the if statement is not met, then the code contained in the else statement will automatically be run.

Let’s try using an else statement in the movie theater problem.

Problem: The local movie theater now wants to recommend The Princess Bride for all viewers who are under 17.

Let’s start with our previous code:

package main

import "fmt"

func main() {
		age := 21
		if age >= 17 {
				fmt.Println("You are allowed to buy a ticket")
		}
}

We just need to add an else statement to recommend The Princess Bride.

		if age >= 17 {
			fmt.Println("You are allowed to buy a ticket")
		} else {
			fmt.Println("Why don't you try the Princess Bride instead")
		}

Now back to your first age line. What would happen if you change the age from 21 to 16? Does it print the right line of code?

PRO TIP: Expected behavior means the code does what you expect it to do. The outcome of a simple function should always have an expected behavior. If it does something you don’t expect, then it is most likely in need of a rewrite. (In part_5 We will use tests to define expected behavior.

Else If Statements

Sometimes when we are programming, we are given problems where we have to define multiple patterns of behavior based on met conditions. We are going to continue using the movie theater problem to explore this.

Problem: The local movie theater has noticed that some small children do not enjoy watching The Princess Bride. The movie theater wants to offer tickets to The Little Mermaid for patrons who are 7 years and younger.

How do we do this? Using only the tools we have so far the code might look something like this:

package main

import (
	"fmt"
- adding tests
- clean up code and add better errors
- add github actions for testing
)

func main() {
	age := 21 
	if age >= 17 {
		fmt.Println("You are allowed to buy a ticket")
	} else {
		if age <= 7 {
			fmt.Println("Would you like to watch The Little Mermaid")
		} else {
			fmt.Println("Why don't you try The Princess Bride instead")
		}
	}

}

This works, but doesn’t this look kind of gross? This code is hard to read, and therefore hard to know what the expected behavior is supposed to be. When code is hard to read, the first thing we should ask ourselves is if there is better way to write this. Simplicity is key.

In Go, and most programming languages, there is a construct called else if that allows us to write this in a more readable way. Else if allows us to add additional condition checks to an if else statement. For example:

package main

import (
	"fmt"
)

func main() {
	age := 21
	if age >= 17 {
		fmt.Println("You are allowed to buy a ticket")
	} else if age <= 7 {
		fmt.Println("Would you like to watch the Little Mermaid")
	} else {
		fmt.Println("Why don't you try the Princess Bride instead")
	}
}

Wasn’t that so much easier? You can add as many else if conditions as needed.

Switch Statements

Additional Practice

Tour of Go

Next Lesson

Continue