Home >Backend Development >Golang >Analysis of how to control the program flow in golang without while

Analysis of how to control the program flow in golang without while

PHPz
PHPzOriginal
2023-04-11 10:42:08665browse

Go language does not have while. Go language provides some basic control statements for controlling program flow.

Basic flow control statements include if, switch, and for. The for statement can implement the function of the while statement.

The syntax structure of for in Go language is as follows:

for 初始语句; 条件语句; 结束语句 {
    循环体语句
}

Example:

package main

import "fmt"

func main() {
    i := 1
    for i <= 3 {
        fmt.Println(i)
        i = i + 1
    }

    for j := 7; j <= 9; j++ {
        fmt.Println(j)
    }

    for {
        fmt.Println("loop")
        break
    }
}

Output:

1
2
3
7
8
9
loop

In the first for loop, use The conditional statement i <= 3 replaces the judgment of the while statement.

In the second for loop, the initial statement j :=7 and the end statement j <= 9 are used to implement an incremental loop.

In the third for loop, no conditional statement and end statement are used. The loop is exited through a conditional judgment break, which simulates while(true).

Generally speaking, although the Go language does not have a while statement, the for statement is highly flexible and can handle all while tasks. Therefore, the while statement is not necessary in Go language.

The above is the detailed content of Analysis of how to control the program flow in golang without while. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn