Breaking Down Go's Control Flow Syntax

Table of Contents

  1. Introduction
  2. Control Flow Statements - if Statement - for Loop - switch Statement - break and continue Statements

  3. Conclusion

Introduction

In this tutorial, we will explore the control flow syntax in the Go programming language. Control flow statements allow us to control the execution order of our program’s statements based on certain conditions.

By the end of this tutorial, you will have a solid understanding of how to use control flow statements such as if statements, for loops, switch statements, break, and continue statements in Go. Let’s get started!

Prerequisites

To follow along with this tutorial, you should have basic knowledge of the Go programming language and have Go installed on your machine. If you haven’t installed Go yet, you can download it from the official Go website.

Control Flow Statements

if Statement

The if statement in Go is used to evaluate a condition and execute a block of code if the condition is true. The basic syntax of an if statement is as follows:

if condition {
    // code to be executed if condition is true
} else {
    // code to be executed if condition is false
}

Here’s an example that demonstrates the usage of an if statement:

package main

import "fmt"

func main() {
    num := 10

    if num%2 == 0 {
        fmt.Println("Number is even")
    } else {
        fmt.Println("Number is odd")
    }
}

In the above example, we check if the number num is even or odd using the modulo operator %. If the remainder is 0, it means the number is even, and the corresponding message is printed. Otherwise, the number is odd, and a different message is printed.

for Loop

The for loop in Go allows us to repeat a block of code multiple times. There are three variations of the for loop in Go: the for loop with a single condition, the for loop that resembles a while loop, and the for loop with a range.

For loop with a Single Condition

The for loop with a single condition has the following syntax:

for initialization; condition; post {
    // code to be executed
}

Here’s an example that demonstrates the usage of a for loop with a single condition:

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        fmt.Println(i)
    }
}

In the above example, the loop initializes the variable i to 1, checks if i is less than or equal to 5, executes the code inside the loop, and increments i by 1 after each iteration. The loop continues until the condition i <= 5 becomes false.

For loop that Resembles a While loop

Sometimes we don’t need an initialization step or a post statement in the for loop. In such cases, we can omit them and create a for loop that resembles a while loop.

Here’s an example that demonstrates the usage of a for loop that resembles a while loop:

package main

import "fmt"

func main() {
    num := 5

    for num > 0 {
        fmt.Println(num)
        num--
    }
}

In the above example, the loop continues as long as the condition num > 0 is true. Inside the loop, we print the value of num and decrement it by 1 after each iteration.

For loop with Range

The for loop with range is used to iterate over elements of an array, slice, string, map, or channel. The syntax for the for loop with range is as follows:

for index, value := range collection {
    // code to be executed
}

Here’s an example that demonstrates the usage of a for loop with range:

package main

import "fmt"

func main() {
    numbers := []int{1, 2, 3, 4, 5}

    for index, value := range numbers {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

In the above example, we iterate over the elements of the numbers slice using the for loop with range. On each iteration, the index represents the current index of the element, and the value represents the value of the element at that index.

switch Statement

The switch statement in Go allows us to select one of many code blocks to be executed based on the value of a variable or expression. The basic syntax of a switch statement is as follows:

switch expression {
case value1:
    // code to be executed if expression equals value1
case value2:
    // code to be executed if expression equals value2
...
default:
    // code to be executed if expression doesn't match any values
}

Here’s an example that demonstrates the usage of a switch statement:

package main

import "fmt"

func main() {
    fruit := "apple"

    switch fruit {
    case "apple":
        fmt.Println("Selected fruit is apple")
    case "banana":
        fmt.Println("Selected fruit is banana")
    case "orange":
        fmt.Println("Selected fruit is orange")
    default:
        fmt.Println("Selected fruit is not apple, banana, or orange")
    }
}

In the above example, we use a switch statement to determine the selected fruit based on the value of the fruit variable.

break and continue Statements

The break statement is used to exit a loop prematurely. When the break statement is encountered inside a loop, the program jumps to the next statement after the loop.

Here’s an example that demonstrates the usage of the break statement:

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            break
        }

        fmt.Println(i)
    }
}

In the above example, when i becomes 3, the break statement is executed, and the loop is terminated prematurely.

The continue statement is used to skip the current iteration of a loop and move to the next iteration.

Here’s an example that demonstrates the usage of the continue statement:

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i == 3 {
            continue
        }

        fmt.Println(i)
    }
}

In the above example, when i becomes 3, the continue statement is encountered, and the current iteration is skipped. The loop continues with the next iteration.

Conclusion

In this tutorial, we covered the control flow syntax in Go. We discussed the if statement, for loops, switch statement, break, and continue statements. By understanding and utilizing these control flow statements effectively, you can have greater control over the execution flow of your Go programs.