Series: Go

Golang Control Flow

Demystify control flow in Go with our comprehensive guide. Master loops, conditionals, and switch statements to enhance your Go programming skills.
E
Edtoks8:53 min read

Control flow statements are the cornerstones of programming, allowing programs to make decisions, repeat actions, and handle different scenarios. Go provides a rich set of control flow statements, enabling programmers to design programs that respond to various conditions and execute code in a structured manner.

Decision-Making with if-else Statements

The if-else statement is the most fundamental control flow structure. It allows a program to execute a block of code if a specific condition is true, and an alternative block of code if the condition is false. This conditional branching enables programs to make decisions based on input data, user choices, or internal state variables.

if Statement:

The if statement in Go is straightforward, evaluating a boolean expression and executing the associated block of code if the condition is true. It is often used for simple conditional checks

package main

import "fmt"

func main() {
    age := 18

    if age >= 18 {
        fmt.Println("You are eligible to vote.")
    }
}

In this example, the program checks if the variable age is greater than or equal to 18. If true, it prints a message indicating eligibility to vote.

if-else Statement:

The if-else statement extends the if statement by providing an alternative block of code to execute when the condition is false.

package main

import "fmt"

func main() {
    age := 16

    if age >= 18 {
        fmt.Println("You are eligible to vote.")
    } else {
        fmt.Println("Sorry, you cannot vote yet.")
    }
}

Else-If Statements:

When there are multiple conditions to check, the else-if statement allows for chaining additional conditions after an initial if statement.

package main

import "fmt"

func main() {

    marks := 85

    if marks >= 90 {
         fmt.Println("Grade A")
    } else if marks >= 80 {
        fmt.Println("Grade B")
    } else if marks >= 70 {
        fmt.Println("Grade C")
    } else {
        fmt.Println("Grade D")
    }
}

Nested if-else Statements:

Nested if-else statements allow for more complex decision-making by embedding if-else structures within each other. This nesting enables programs to handle multiple conditions and make more granular decisions based on specific criteria.

package main

import "fmt"

func main() {
    age := 15
    height := 170

    if age >= 18 {
        if height >= 160 {
            fmt.Println("You can ride the roller coaster.")
        } else {
            fmt.Println("You cannot ride the roller coaster due to height restrictions.")
        }
    } else {
        fmt.Println("You cannot ride the roller coaster due to age restrictions.")
    }
}

Repetition with Loops: Iterating over Data

Loops allow a program to repeatedly execute a block of code until a specific condition is met. They are essential for processing collections of data, performing repetitive tasks, and controlling the flow of execution based on specific criteria.

for Loops:

The for loop is the most versatile looping construct in Go. It allows defining a starting point, an exit condition, and an increment step for controlling the loop's iterations.

The basic syntax includes the initialization statement, condition, and post iteration statement.

package main

import "fmt"

func main() {
    // Basic for loop
    for i := 1; i <= 5; i++ {
        fmt.Println("Count:", i)
    }
}

In this example, the loop iterates from 1 to 5, printing the count at each iteration. The for loop is flexible and can be adapted for various scenarios.

for-range Loops:

The for-range loop is specifically designed for iterating over collections of data, such as arrays, slices, maps, and channels. It automatically extracts each element from the collection and assigns it to a variable within the loop body.

package main

import "fmt"

func main() {
    // Looping through a collection (slice)
    names := []string{"Alice", "Bob", "Charlie"}

    for index, name := range names {
        fmt.Println("Index:", index, "Name:", name)
    }
}

Here, the loop iterates through a slice of names, providing both the index and the corresponding name at each iteration.

For Loop with Break Statement:

The break statement in Go is used to exit a loop prematurely. It is commonly employed to terminate a loop based on a certain condition.

package main

import "fmt"

func main() {
    for i := 1; i <= 10; i++ {
        if i == 5 {
            fmt.Println("Breaking at", i)
            break
        }
        fmt.Println(i)
    }
}

In this example, the loop iterates from 1 to 10. When the value of i reaches 5, the break statement is executed, and the loop terminates. The output will be:

1
2
3
4
Breaking at 5

For Loop with Continue Statement:

The continue statement is used to skip the rest of the loop's body and jump to the next iteration. It is handy when specific conditions should trigger the skipping of some iterations.

package main

import "fmt"

func main() {
    for i := 1; i <= 5; i++ {
        if i%2 == 0 {
            fmt.Println("Skipping even number:", i)
            continue
        }
        fmt.Println("Processing odd number:", i)
    }
}

In this example, the loop iterates from 1 to 5. The continue statement is executed when the value of i is an even number, skipping the print statement for even values. The output will be:

Processing odd number: 1
Skipping even number: 2
Processing odd number: 3
Skipping even number: 4
Processing odd number: 5

These examples showcase how the break and continue statements can be used within for loops to control the flow of execution. The break statement allows for premature exit from a loop, while the continue statement enables skipping specific iterations based on conditions. Understanding and using these statements strategically can lead to more efficient and readable code in Go.

Infinite for loop

package main

import "fmt"

func main() {
    // Infinite loop with break statement
    counter := 0

    for {
        fmt.Println("Counter:", counter)
        counter++

        if counter == 5 {
            break
        }
    }
}

In this example, an infinite loop is created, but the break statement is used to exit the loop when the counter reaches a certain value.

while Loops:

The while loop executes a block of code as long as a specified condition remains true. It continues iterating until the condition evaluates to false.

package main

import "fmt"

func main() {
    i := 0

    while i < 10 {
        fmt.Println(i)
        i++
    }
}

Switch

In Go, the switch statement is a powerful and flexible control flow construct used for making decisions based on the value of an expression. It is a concise and expressive alternative to multiple if-else statements.

Basic Switch Statement:

The basic syntax of a switch statement involves evaluating an expression and comparing it against different possible values.

package main

import "fmt"

func main() {
    day := "Wednesday"

    switch day {
    case "Monday":
        fmt.Println("It's the start of the week.")
    case "Wednesday":
        fmt.Println("It's the middle of the week.")
    case "Friday":
        fmt.Println("It's the end of the week.")
    default:
        fmt.Println("It's another day.")
    }
}

In this example, the switch statement evaluates the value of the day variable and executes the corresponding case. The output will be:

It's the middle of the week.

Switch Statement with Multiple Conditions:

The switch statement can be used without an expression, and each case condition is evaluated independently.

package main

import "fmt"

func main() {
    score := 75

    switch {
    case score >= 90:
        fmt.Println("Excellent!")
    case score >= 70:
        fmt.Println("Good job!")
    default:
        fmt.Println("You can do better.")
    }
}

In this example, the switch statement evaluates multiple conditions for the score variable and prints a corresponding message.

Type Switch:

The switch statement can be used for type-switching, where it evaluates the type of an interface value.

package main

import "fmt"

func checkType(x interface{}) {
    switch x.(type) {
    case int:
        fmt.Println("It's an integer.")
    case float64:
        fmt.Println("It's a floating-point number.")
    case string:
        fmt.Println("It's a string.")
    default:
        fmt.Println("It's another type.")
    }
}

func main() {
    checkType(42)
    checkType(3.14)
    checkType("Hello, Go!")
    checkType(true)
}

In this example, the checkType function uses a type-switch inside a switch statement to determine the type of the argument passed.

Fallthrough in Switch:

Go allows the use of the fallthrough keyword to transfer control to the next case even if the condition is not met.

package main

import "fmt"

func main() {
    num := 2

    switch num {
    case 1:
        fmt.Println("One")
        fallthrough
    case 2:
        fmt.Println("Two")
        fallthrough
    case 3:
        fmt.Println("Three")
    }
}

In this example, the fallthrough statement causes the control flow to move to the next case after the matching one, resulting in the output:

Two
Three

The switch statement in Go is a versatile tool for decision-making. It supports both simple and complex conditions, allowing developers to write concise and readable code. The ability to switch on types makes it especially powerful in scenarios involving interface values.

Conclusion

Control flow statements are the backbone of programming, enabling programs to make decisions, repeat actions, and handle different scenarios effectively. Go's control flow statements, including if-else, else-if, and loops, provide a powerful and flexible toolkit for designing robust and efficient programs. By mastering these control flow structures, programmers can create software that adapts to various conditions, processes data efficiently, and responds to user input and external stimuli in a structured and meaningful way.