Control Flow in Go: Conditional Statements and Loops

January 21, 2024

Here, we cover the control flow mechanisms in Go, including conditional statements and loops. Readers will understand how to use if-else statements, switch cases, and various types of loops to control the flow of their Go programs.

Conditional Statements

In Go, conditional statements are used to perform different actions based on certain conditions. The if statement is used to execute a block of code if a specified condition is true. Here’s an example:

package main

import (
    "fmt"
)

func main() {
    x := 10
    if x > 5 {
        fmt.Println("x is greater than 5")
    } else {
        fmt.Println("x is less than or equal to 5")
    }
}

In this example, the value of x is checked, and based on the condition, the appropriate message is printed.

Switch Statements

Switch statements in Go are used to select one of many code blocks to be executed. The expression in the switch statement is evaluated once, and its value is compared with the values of each case. Here’s an example:

package main

import (
    "fmt"
)

func main() {
    day := "Monday"
    switch day {
    case "Monday":
        fmt.Println("Today is Monday")
    case "Tuesday":
        fmt.Println("Today is Tuesday")
    default:
        fmt.Println("It's neither Monday nor Tuesday")
    }
}

In this example, based on the value of day, the corresponding message is printed.

Loops

Loops are used to execute a block of code repeatedly. Go supports various types of loops, including for, for...range, and while loops.

The for loop is used to repeatedly execute a block of code as long as a specified condition is true. Here’s an example:

package main

import (
    "fmt"
)

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

In this example, the loop will print the numbers from 1 to 5.

The for...range loop is used to iterate over elements in a data structure such as an array, slice, or map. Here’s an example:

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 this example, the loop will iterate over the elements of the numbers slice and print the index and value of each element.

The while loop is not directly supported in Go, but it can be simulated using the for loop with a conditional statement. Here’s an example:

package main

import (
    "fmt"
)

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

In this example, the for loop is used to simulate a while loop that prints the numbers from 1 to 5.