Go's for loop

In the Go language, loops are implemented with the for keyword. Go language provides three basic loop modes: for loop, range loop and for...range loop.

for loop:

for 初始化语句; 循环条件; 循环后执行语句 {
    // 循环体代码
}

The initialization statement is used to initialize the loop variable; the loop body code is executed when the loop condition is true; the execution statement after the loop is executed after each loop ends. For example:

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

The above code will output a number from 0 to 4.

range loop:

The range loop is used to traverse the elements of data structures such as arrays, slices, strings, and maps.

for index, value := range collection {
    // 循环体代码
}

index is the index of the current element, and value is the value of the current element. For example:

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

The above code will output the index and value of each element in the numbers array.

for...range loop:

A for...range loop can be used to iterate over the values ​​in a channel until the channel is closed.

for value := range channel {
    // 循环体代码
}

value is the value received from the channel. For example:

ch := make(chan int)
go func() {
    ch <- 1
    ch <- 2
    close(ch)
}()
for value := range ch {
    fmt.Println(value)
}

The above code will output the values ​​1 and 2 in the channel ch.

In addition to the above-mentioned basic looping methods, the Go language also provides break and continue statements to control the jump of the flow in the loop. The break statement is used to terminate the current loop and jump out of the loop body; the continue statement is used to skip the remaining code of the current loop and enter the next loop iteration.

Guess you like

Origin blog.csdn.net/weixin_62264287/article/details/132493973