Go if, else & switch Conditional Control Tutorial

In this Go tutorial we learn how to control the flow of our application through conditional logic with if, else if, else and switch statements.

We also take a look at how to nest conditional control structures inside others.

What is conditional control

We can control the flow of our Go application by evaluating certain conditions, and executing sections of code based on the result.

As an example, let’s consider an application with a member area. To gain access to the member area, a user must provide the correct login credentials.

If the user provides the correct credentials, they are allowed to enter the member area. If not, they are given the option to try again or reset their password.

In pseudocode, the example above would look something like this.

Example:
if username == db_username && password == db_password
	redirect to member area
otherwise
	if forgot_password
		reset password
otherwise
	try_again

Our actual code will not look like the example above, but it serves to give you an example of what conditional control is used for.

We can use conditional control through the following statements, in combination with comparison and logical operators.

  • if
  • else if
  • else
  • switch

The if statement

The if statement will evaluate if a condition proves true. If it does, the compiler will execute the if statement’s code block. If not, the compiler will move on to the following statement below the code block.

An if statement is written with the keyword if , followed by the condition(s) we want to evaluate between parentheses.

Then, we specify a code block with open and close curly braces that will be executed if the condition proves true.

Syntax:
if (condition) {

    // code to execute
    // if condition is
    // true
}
Example:
package main

import "fmt"

func main() {

    num1 := 5
    num2 := 5

    if (num1 == num2) {

        fmt.Printf("%d is equal to %d", num1, num2)
    }
}

In the example above, the if statement compares the two numbers to see if they are the same. Because they are, the message is printed to the console.

If we change one of the numbers to another value, the condition will be false and the message will not be printed.

Example:
package main

import "fmt"

func main() {

    num1 := 5
    num2 := 3

    if (num1 == num2) {

        fmt.Printf("%d is equal to %d", num1, num2)
    }
}

When we run the example above, nothing is printed to the console because the condition is false and the print statement never gets executed.

The else if ladder

We use the else if ladder when we want to evaluate extra conditions.

To create an else if ladder, we simply add the word else between two if statements, connecting them.

Syntax:
if (condition1) {

    // first condition
    // to be evaluated
}
else if (condition2) {

    // second condition
    // to be evaluated
}
Example:
package main

import "fmt"

func main() {

    num1 := 5
    num2 := 3

    if (num1 < num2) {

        fmt.Printf("first if condition is true")

    } else if (num1 > num2) {

        fmt.Printf("second if condition is true")
    }
}

We use else if ladders to connect our if statements together, sort of grouping them.

Note that an else if statement can only follow an if statement, it cannot stand on its own. The first conditional must always be an if.

The else fallback

The else statement acts as a catch-all fallback for anything that isn’t covered by an if statement or an else if ladder.

Because it works as a catch-all, the else statement doesn’t need a conditional block in the header. We only write the keyword else, followed by an execution block.

Syntax:
if (condition) {

    // code to execute
    // if condition is
    // true
}
else {

    // if above conditions
    // are false, execute
    // this block
}

As with the else if ladder, the else statement cannot stand on its own. It must follow an if statement or else if ladder.

Example:
package main

import "fmt"

func main() {

    num1 := 5
    num2 := 5

    if (num1 < num2) {

        fmt.Printf("if condition is true")

    } else if (num1 > num2) {

        fmt.Printf("else if condition is true")

    } else {

        fmt.Printf("nothing above is true, execute else fallback")
    }
}

In the example above, our else execution block is executed because both if statements prove false.

Nested if statements

We can nest if statements inside other if statements. The compiler will evaluate each if statement in a hierarchical fashion.

All we do is write an if statement inside the execution block of another if statement.

Example:
package main

import "fmt"

func main() {

    a := 10

    if (a < 20) {

        fmt.Println("outer if");

        // nested if
        if (a >= 10) {
            fmt.Println("inner if");
        }
    }
}

We’re not limited to one if statement. We can have as many if conditions as we need in one control structure set.

That said, don’t nest more than three levels deep. Nested conditionals that nest too deep is a bad practice, in most situations we can use loops to simplify the process.

Go Ternary operator (?:)

The Go developers have chosen not to include the ternary operator stating that they’ve seen the operation used too often to create impenetrably complex expressions.

The Switch statement

The switch statement is used when we want to compare a single value against a list of values.

Before we explain how it works, let’s look at the syntax first.

Syntax:
switch main_value {

    case check_against_value1 :
        // if true execute this code
    case check_against_value2 :
        // if true execute this code
    default:
        // if none of the cases are true
}

First, we specify our main value that we will be comparing other values against. Then, in the code block, we specify our cases.

A case consists of the value we want to compare against the main value, and execution code after the : if the comparison proves true.

The default case acts as our fallback statement, much like an else statement. In fact, the switch statement above is comparable to the following if statement.

Syntax:
if (main_value == check_against_value1) {

    // if true execute this code
} else if (main_value == check_against_value2) {

    // if true execute this code
} else {

    // if none of the cases are true
}

Let’s see a real world example.

Example:
package main

import "fmt"

func main() {

    grade := 'B';

    switch grade {
        case 'A':
            fmt.Println("Excellent!");
        case 'B':
            fmt.Println("Very good");
        case 'C':
            fmt.Println("Well done");
        case 'D':
            fmt.Println("You passed");
        case 'F':
            fmt.Println("You failed");
        default:
            fmt.Println("Invalid grade");
    }

    fmt.Println("Your grade is", grade);
}

In the example above, we have a single main value (grade) that’s being evaluated against multiple cases. When a case evaluates to true, the execution statement after the colon executes.

Typically a switch statement is only used when we want to compare one value to many others.

Summary: Points to remember

  • Conditional control allows us to control the flow of our application through conditional logic.
  • Go provides us with the if, else if, else and switch conditional control statements.
  • The else if ladder and else statement cannot stand on their own, they must be part of an if statement.
  • The else statement represents everything that the if and else if statements do not cover.
  • We can nest conditionals by writing them inside the execution blocks of other conditionals.
  • Go does not have a ternary operator.
  • A switch statement is used to compare one value against many.