CodeToLive

Control Structures in Go

Control structures in Go allow you to control the flow of your program. They include conditional statements (if-else, switch) and loops (for). These structures are essential for making decisions and repeating tasks in your code.

If-Else Statements

The if-else statement is used to execute a block of code based on a condition. You can also use else if to check multiple conditions.


package main

import "fmt"

func main() {
    age := 20
    if age >= 18 {
        fmt.Println("You are an adult.")
    } else if age >= 13 {
        fmt.Println("You are a teenager.")
    } else {
        fmt.Println("You are a child.")
    }
}
      

Switch Statement

The switch statement is used to execute one of many code blocks based on the value of an expression. It is often used as an alternative to multiple if-else statements.


package main

import "fmt"

func main() {
    day := 3
    switch day {
    case 1:
        fmt.Println("Monday")
    case 2:
        fmt.Println("Tuesday")
    case 3:
        fmt.Println("Wednesday")
    default:
        fmt.Println("Invalid day")
    }
}
      

Loops

Go has only one looping construct: the for loop. It can be used in various ways:


package main

import "fmt"

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

    // While-like loop
    count := 0
    for count < 5 {
        fmt.Println("While Loop:", count)
        count++
    }

    // Infinite loop
    for {
        fmt.Println("This will run forever.")
        break // Exit the loop
    }
}
      

Nested Loops

Loops can be nested inside other loops to handle more complex scenarios, such as working with multi-dimensional arrays.


package main

import "fmt"

func main() {
    for i := 0; i < 3; i++ {
        for j := 0; j < 3; j++ {
            fmt.Printf("i = %d, j = %d\n", i, j)
        }
    }
}
      

Break and Continue

The break statement is used to exit a loop prematurely. The continue statement skips the rest of the loop body and proceeds to the next iteration.


package main

import "fmt"

func main() {
    // Break Example
    for i := 0; i < 10; i++ {
        if i == 5 {
            break // Exit the loop when i is 5
        }
        fmt.Println("Break Example:", i)
    }

    // Continue Example
    for i := 0; i < 10; i++ {
        if i%2 == 0 {
            continue // Skip even numbers
        }
        fmt.Println("Continue Example:", i)
    }
}
      

Best Practices

Next: Functions