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

PHPz
Release: 2023-04-11 11:37:10
Original
596 people have browsed it

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 初始语句; 条件语句; 结束语句 {
    循环体语句
}
Copy after login

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
    }
}
Copy after login

Output:

1
2
3
7
8
9
loop
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!