Table of Contents
2. Loop statement" >2. Loop statement
2.1 Loop processing statement " >2.1 Loop processing statement
##2.2 Loop control statement" >##2.2 Loop control statement
Home Backend Development Golang What are the golang flow control statements?

What are the golang flow control statements?

Dec 28, 2022 pm 05:58 PM
golang go language process control

Flow control statement: 1. if statement, consisting of a Boolean expression followed by one or more statements; 2. "if...else" statement, the expression in else is false in the Boolean expression executed; 3. switch statement, used to perform different actions based on different conditions; 4. select statement; 5. for loop statement, syntax "for k,v := range oldmap{newmap[k]=v}"; 6. Loop control statements break, continue, goto.

What are the golang flow control statements?

The operating environment of this tutorial: Windows 7 system, GO version 1.18, Dell G3 computer.

Let’s take a look at the basic content of golang flow control statements.

1. Conditional branch statement

is similar to the C language. The relevant conditional statements are as shown in the following table:

Statement Description
if statement if statement consists of a Boolean expression Followed by one or more statements.
if…else statement The optional else statement can be used after the if statement. The expression in the else statement is executed when the Boolean expression is false.
switch statement The switch statement is used to perform different actions based on different conditions.
select statement The select statement is similar to the switch statement, but select will randomly execute a runnable case. If there is no case to run, it will block until there is a case to run.
  • if statement
    The syntax is as follows:
if 布尔表达式 {
   /* 在布尔表达式为 true 时执行 */
}
Copy after login
  • if-else statement
if 布尔表达式 {
   /* 在布尔表达式为 true 时执行 */
} else {
	/* 在布尔表达式为 false 时执行 */
}
Copy after login
  • switch statement
    The variable <span class="hljs-attribute">v</span> can be of any type, val1 and val2 can be the same Any value of type, the type is not limited to constants or integers, or the final result is an expression of the same type.
switch v {
    case val1:
        ...
    case val2:
        ...
    default:
        ...
}
Copy after login
  • select statement
    select is a control structure in Go, similar to the switch statement used for communication. Each case must be a communication operation, either a send or a receive. It will randomly execute a runnable case. If there is no case to run, it will block until there is a case to run. A default clause should always be runnable.
select {
    case communication clause  :
       statement(s);      
    case communication clause  :
       statement(s);
    /* 你可以定义任意数量的 case */
    default : /* 可选 */
       statement(s);
}
Copy after login

Note:

  • Each case must be a communication
  • All channel expressions will be evaluated and all sent The expressions will be evaluated
  • If any one of the communications can be executed, it will be executed, and the others will be ignored
  • If there are multiple cases that can be executed, select will randomly select one. implement.
  • If no case can be run: If there is a default clause, the default clause will be executed, and the select will be blocked until a certain communication can run, thus avoiding the starvation problem.

2. Loop statement

2.1 Loop processing statement

Different from most languages, the loop statement in Go language only supports the for keyword and does not support the while and do-while structures. The basic usage of the keyword for is very close to that in C language and C .

For is used to implement loops in Go. There are three forms:


Syntax
is the same as for in c language for init; condition; post {}
is the same as for in c language The while is the same as for condition{}
and <span class="hljs-function"><span class="hljs-title">for</span><span class="hljs-params">(;;) in c language </span></span>Samefor{}

In addition, the for loop can also be used directlyrangeIterate over slices, maps, arrays and strings, etc., the format is as follows:

for key, value := range oldmap {
	newmap[key] = value
}
Copy after login

##2.2 Loop control statement

Control statementDetailed explanationbreakInterrupt out of the loop or switch statementcontinueSkip the remaining statements of the current loop, and then continue with the next round of loopsgoto statementwill Control transfers to the marked statement

1、break

break主要用于循环语句跳出循环,和c语言中的使用方式是相同的。且在多重循环的时候还可以使用label标出想要break的循环。
实例代码如下:

a := 0
for a<5 {
	fmt.Printf("%d\n", a)
	a++
	if a==2 {
		break;
	}
}
/* output
0
1
2
*/
Copy after login

2、continue

Go 语言的 continue 语句 有点像 break 语句。但是 continue 不是跳出循环,而是跳过当前循环执行下一次循环语句。在多重循环中,可以用标号 label 标出想 continue 的循环。
实例代码如下:

    // 不使用标记
    fmt.Println("---- continue ---- ")
    for i := 1; i <= 3; i++ {
        fmt.Printf("i: %d\n", i)
            for i2 := 11; i2 <= 13; i2++ {
                fmt.Printf("i2: %d\n", i2)
                continue
            }
    }

/* output
i: 1
i2: 11
i2: 12
i2: 13
i: 2
i2: 11
i2: 12
i2: 13
i: 3
i2: 11
i2: 12
i2: 13
*/

    // 使用标记
    fmt.Println("---- continue label ----")
    re:
        for i := 1; i <= 3; i++ {
            fmt.Printf("i: %d", i)
                for i2 := 11; i2 <= 13; i2++ {
                    fmt.Printf("i2: %d\n", i2)
                    continue re
                }
        }

/* output
i: 1
i2: 11
i: 2
i2: 11
i: 3
i2: 11
*/
Copy after login

3、goto

goto语句主要是无条件转移到过程中指定的行。goto语句通常和条件语句配合使用,可用来实现条件转移、构成循环以及跳出循环体等功能。但是并不主张使用goto语句,以免造成程序流程混乱。
示例代码如下:

var a int = 0
LOOP: for a<5 {
	if a == 2 {
		a = a+1
		goto LOOP
	}
	fmt.Printf("%d\n", a)
	a++
}

/*
output:
0
1
2
3
4
*/
Copy after login

以上代码中的LOOP就是一个标签,当运行到goto语句的时候,此时执行流就会跳转到LOOP标志的哪一行上。

【相关推荐:Go视频教程编程教学

The above is the detailed content of What are the golang flow control statements?. For more information, please follow other related articles on the PHP Chinese website!

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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Hot Topics

Java Tutorial
1662
14
PHP Tutorial
1261
29
C# Tutorial
1234
24
How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? How to solve the user_id type conversion problem when using Redis Stream to implement message queues in Go language? Apr 02, 2025 pm 04:54 PM

The problem of using RedisStream to implement message queues in Go language is using Go language and Redis...

What is the problem with Queue thread in Go's crawler Colly? What is the problem with Queue thread in Go's crawler Colly? Apr 02, 2025 pm 02:09 PM

Queue threading problem in Go crawler Colly explores the problem of using the Colly crawler library in Go language, developers often encounter problems with threads and request queues. �...

What should I do if the custom structure labels in GoLand are not displayed? What should I do if the custom structure labels in GoLand are not displayed? Apr 02, 2025 pm 05:09 PM

What should I do if the custom structure labels in GoLand are not displayed? When using GoLand for Go language development, many developers will encounter custom structure tags...

What libraries are used for floating point number operations in Go? What libraries are used for floating point number operations in Go? Apr 02, 2025 pm 02:06 PM

The library used for floating-point number operation in Go language introduces how to ensure the accuracy is...

Which libraries in Go are developed by large companies or provided by well-known open source projects? Which libraries in Go are developed by large companies or provided by well-known open source projects? Apr 02, 2025 pm 04:12 PM

Which libraries in Go are developed by large companies or well-known open source projects? When programming in Go, developers often encounter some common needs, ...

In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? In Go programming, how to correctly manage the connection and release resources between Mysql and Redis? Apr 02, 2025 pm 05:03 PM

Resource management in Go programming: Mysql and Redis connect and release in learning how to correctly manage resources, especially with databases and caches...

How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? How to solve the problem of Golang generic function type constraints being automatically deleted in VSCode? Apr 02, 2025 pm 02:15 PM

Automatic deletion of Golang generic function type constraints in VSCode Users may encounter a strange problem when writing Golang code using VSCode. when...

Golang's Purpose: Building Efficient and Scalable Systems Golang's Purpose: Building Efficient and Scalable Systems Apr 09, 2025 pm 05:17 PM

Go language performs well in building efficient and scalable systems. Its advantages include: 1. High performance: compiled into machine code, fast running speed; 2. Concurrent programming: simplify multitasking through goroutines and channels; 3. Simplicity: concise syntax, reducing learning and maintenance costs; 4. Cross-platform: supports cross-platform compilation, easy deployment.

See all articles