Golang Tutorial

Fundamentals

Control Statements

Functions & Methods

Structure

Arrays & Slices

String

Pointers

Interfaces

Concurrency

Loop Control Statements in Golang

Loop control statements are used to handle the flow of a loop. In Go (often referred to as Golang), the primary looping construct is the for loop. There isn't a while or do-while loop like in some other languages, but the for loop in Go is quite flexible and can be used in various ways to mimic the behavior of these loops.

Here's a breakdown of the loop control statements in Go, along with examples:

  • Basic for Loop: This is the most common looping construct. It consists of three parts: the initialization, the condition, and the post statement.
for initialization; condition; post {
    // code to be executed in the loop
}

Example:

package main

import "fmt"

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

This will print:

0
1
2
3
4
  • Condition-only for Loop: This is similar to the while loop in other languages.
for condition {
    // code to be executed in the loop
}

Example:

package main

import "fmt"

func main() {
    i := 0
    for i < 5 {
        fmt.Println(i)
        i++
    }
}
  • Infinite for Loop: A loop without a condition will run indefinitely, unless broken by an external factor like a break statement.
for {
    // code to be executed in the loop
}

Example:

package main

import "fmt"

func main() {
    i := 0
    for {
        fmt.Println(i)
        i++
        if i >= 5 {
            break
        }
    }
}
  • break Statement: The break statement is used to terminate the loop prematurely.

Example:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i == 5 {
            break
        }
        fmt.Println(i)
    }
}
  • continue Statement: The continue statement is used to skip the rest of the loop's current iteration and jump to the next iteration.

Example:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i == 5 {
            continue
        }
        fmt.Println(i)
    }
}
  • for with range: This is used to iterate over elements of collections like arrays, slices, strings, maps, and channels.

Example:

package main

import "fmt"

func main() {
    nums := []int{1, 2, 3, 4, 5}
    for index, value := range nums {
        fmt.Printf("Index: %d, Value: %d\n", index, value)
    }
}

In this tutorial, we've gone over the basic loop control statements in Golang. Remember, practice makes perfect. The more you work with these constructs, the more comfortable you'll become.

  1. Using break and continue in Golang loops:

    • Description: Introduction to using break and continue statements in Golang loops for control flow.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          // Using break to exit the loop
          for i := 1; i <= 5; i++ {
              if i == 3 {
                  break
              }
              fmt.Println(i)
          }
      
          // Using continue to skip an iteration
          for i := 1; i <= 5; i++ {
              if i == 3 {
                  continue
              }
              fmt.Println(i)
          }
      }
      
  2. How to exit a loop early in Golang:

    • Description: Exiting a loop early using the break statement based on a condition.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          for i := 1; i <= 5; i++ {
              if i == 3 {
                  break
              }
              fmt.Println(i)
          }
      }
      
  3. Loop control with labeled statements in Golang:

    • Description: Using labeled statements to control the flow of nested loops in Golang.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          outerLoop:
          for i := 1; i <= 3; i++ {
              for j := 1; j <= 3; j++ {
                  fmt.Println(i, j)
                  if i*j == 6 {
                      break outerLoop
                  }
              }
          }
      }
      
  4. Golang for loop examples with break and continue:

    • Description: Examples of Golang for loops incorporating break and continue statements.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          // Example with break
          for i := 1; i <= 5; i++ {
              if i == 3 {
                  break
              }
              fmt.Println("Break:", i)
          }
      
          // Example with continue
          for i := 1; i <= 5; i++ {
              if i == 3 {
                  continue
              }
              fmt.Println("Continue:", i)
          }
      }
      
  5. Exiting nested loops in Golang:

    • Description: Exiting from nested loops using labeled statements and the break statement.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          outerLoop:
          for i := 1; i <= 3; i++ {
              for j := 1; j <= 3; j++ {
                  fmt.Println(i, j)
                  if i*j == 6 {
                      break outerLoop
                  }
              }
          }
      }
      
  6. Labeling loops for precise control in Golang:

    • Description: Labeling loops to gain precise control and facilitate the use of labeled statements for loop control.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          outerLoop:
          for i := 1; i <= 3; i++ {
              for j := 1; j <= 3; j++ {
                  fmt.Println(i, j)
                  if i*j == 6 {
                      break outerLoop
                  }
              }
          }
      }
      
  7. Using goto for loop control in Golang (note: goto should be used with caution):

    • Description: Demonstrating the use of the goto statement for loop control. Note that the usage of goto should be approached with caution.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          i := 1
          startLoop:
          if i > 5 {
              goto endLoop
          }
          fmt.Println(i)
          i++
          goto startLoop
          endLoop:
      }
      
  8. Common loop control patterns and idioms in Golang:

    • Description: Showcasing common patterns and idioms used for loop control in Golang, including breaking out of an infinite loop and iterating over a collection.

    • Code:

      package main
      
      import "fmt"
      
      func main() {
          // Breaking out of an infinite loop
          i := 1
          for {
              if i > 5 {
                  break
              }
              fmt.Println(i)
              i++
          }
      
          // Iterating over a collection (slice)
          numbers := []int{1, 2, 3, 4, 5}
          for _, num := range numbers {
              fmt.Println(num)
          }
      }