1 Overview of Loop Statements

In Go language, loop statements allow us to execute a code block multiple times. When you need to repeatedly perform certain operations, loop statements become very useful. For example, you may want to iterate through each element in an array, or repeat an operation until a specific condition is met. In Go, loop statements are mainly implemented using the for keyword, which is the only loop statement in the Go language. Correct use of loop statements is crucial for writing efficient and maintainable code.

2 Basics of for Loop

2.1 Structure of for Loop

The for loop in Go language consists of three parts:

  1. Initialization statement: executed before the first iteration, usually used to declare a loop counter.
  2. Condition expression: evaluated before each iteration. If the condition is true, the loop body is executed.
  3. Post statement: executed after the code block of each iteration, usually used to update the loop counter.

The syntax of the for loop is as follows:

for initialization statement; condition expression; post statement {
    // loop body code
}

2.2 Simple Example of for Loop

Let's understand the execution process of the for loop through a simple example:

package main

import "fmt"

func main() {
    for i := 0; i < 5; i++ {
        fmt.Println("The value of i is:", i)
    }
}

In this example, the variable i is initialized to 0. The for loop checks if the condition i < 5 is true. If the condition is true, the loop body is executed and the value of i is printed. After executing the loop body, the value of i is updated by i++ (increment operation), and then the loop rechecks the condition until the value of i reaches 5, at which point the condition becomes false and the for loop terminates.

2.3 Other for Loop Examples

The for loop in Go language is very flexible and can be written in various forms to handle different scenarios.

2.3.1 Infinite Loop

In Go, you can omit the initialization statement, the condition expression, and the post statement of the for loop, creating an infinite loop that will run until terminated by a break statement or a return value from a function.

for {
    // Code within an infinite loop
    if someCondition {
        break // Exit the loop when a certain condition is met
    }
}

2.3.2 Loop with Only Condition

In Go, you can also use a for loop that contains only a condition, similar to a while loop in other programming languages.

n := 0
for n < 5 {
    fmt.Println(n)
    n++
}

The above code will print 0 to 4, and the loop will end when n reaches 5.

2.3.3 Loop through an array or slice

In Go, the range keyword is used to simplify the iteration through each element of an array or slice.

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

The above code will print the index and value of each element. If you only need the value of the elements, you can use _ to ignore the index.

for _, value := range items {
    fmt.Printf("Value: %d\n", value)
}

Note: The usage of arrays will be explained in detail in subsequent chapters. If you don't understand this part, it's okay as long as you understand that for loop can be used this way.

2.3.4 Loop through maps

When iterating through a map, the combination of for loop and range expression is very powerful. This allows you to get each key-value pair of the map.

colors := map[string]string{"red": "#ff000", "green": "#00ff00", "blue": "#000ff"}
for key, value := range colors {
    fmt.Printf("Key: %s, Value: %s\n", key, value)
}

In this example, we print all the keys and their corresponding values in the colors map. Similar to iterating through slices, if you only need the key or value, you can choose to ignore the other.

Note: The usage of maps will be explained in detail in subsequent chapters. If you don't understand this part, it's okay as long as you understand that for loop can be used this way.

3 Control the flow of loops

3.1 Use break to end a loop

Sometimes we need to exit the loop prematurely when a specific condition is met, and in such cases, the break statement can be used. Below is an example of using break to exit a loop:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i == 5 {
            break // Exit the loop when i equals 5
        }
        fmt.Println("The value of i is:", i)
    }
    // The output will only contain values from 0 to 4
}

3.2 Use continue to skip iterations

In certain situations, we may want to skip the current iteration and proceed with the next iteration in the loop. This can be achieved using the continue statement. Here's an example:

package main

import "fmt"

func main() {
    for i := 0; i < 10; i++ {
        if i%2 != 0 {
            continue // Skip this iteration if i is odd
        }
        fmt.Println("Even number:", i)
    }
}