In this class, we’ll be covering how you can use conditionals in Golang. So, let’s dive in and find out how to use conditionals in Golang.

You might be thinking, “What are conditionals?”

Well, conditionals are expressions that result to either true or false when evaluated. The main purpose of using conditionals is to help in controlling the program flow during execution. Two conditionals are employed in Golang. These are:

•If else statement

•Switch statement

Let’s dive in and find out how you can use these conditionals.

#1: If else statement
In Golang, a simple if statement has the following form:

if Boolean expression
{
Statements
}

Here’s an example of a code that tests if the average score is greater than or equal to 80 and displays grade “A”.

if average&amp;gt;=80
{
grade=”A.”
}

An if statement can only be executed when the Boolean expression is true. Otherwise, the statement is skipped. In some cases, if statement can be followed by an else statement that is optional. When you have an optional if statement, the optional statement executes only when the Boolean expression is false. Here’s the syntax:

if Boolean expression
{
Statement(s) /* they can only execute when the Boolean expressions are true*/
}
else
{
Statement(s) /* they can only execute when the Boolean expressions are false*/
}

Note that the Boolean expression is not enclosed in brackets. Here’s an example of if statement that has optional else statement:

#2: The Switch Statement
The switch statement enables a variable to be tested for equivalence against a set of values where each value—commonly referred to as the case—is the variable that’s checked for each switch case. There are two types of defining the switch statement. These are:

•The expression switch.

•The type switch.

While the expression switch statement has expressions that are compared against the value for each of the switch expressions, the type switch contains the types that are compared against the type of special annotated switch expressions.