banner
音小董

哩哔哩哔

这世上的热闹出自孤单

Chapter 5: Flow Control

Introduction#

Control statement categories:

  1. Sequential structure
  2. Branching structure
  3. Loop structure
    Control Flow.png

Branching Structure#

if branch#

Single branch#

Basic syntax
if condition {
logic code
}
The logic code in {} is only executed when the condition expression is true

  1. () can be added on both sides of the condition expression, but it is recommended not to add them.
  2. There must be a space between If and the condition expression.
  3. {} must be present.

Result:

Double branch#

Basic syntax
if condition {
logic code 1
} else {
logic code 2
}
When the condition expression is true, execute logic code 1; otherwise, execute logic code 2

Result:

Multiple branches#

Basic syntax
if condition {
logic code 1
} else {
logic code 2
}
......
else {
logic code n
}
Execute in order. When one condition expression is true, execute the corresponding logic code and end the execution without continuing to execute

Result:

switch branch#

Basic syntax
switch expression {
case value 1, value 2, ......:
statement block 1
Case value 3, value 4, ......:
statement block 2
......
default:
statement block
}
Execute in order. When one case satisfies the expression, execute the corresponding statement block and end the execution without continuing to execute
Student Scores.png

Result:

Loop Structure#

for loop#

Basic syntax
for (initial expression; boolean expression; iteration factor){
loop body;
}

for range#

Can traverse arrays, slices, strings, maps, and channels

Basic syntax
for key, val := range coll {

}

Result:

Keywords#

break#

Execute the current loop and then exit the entire loop

Result:

continue#

Exit the current loop and continue with the next loop

Result:

goto#

Jump to the specified line and execute

Result:

return#

End the current function without continuing to execute

Result:

Loading...
Ownership of this post data is guaranteed by blockchain and smart contracts to the creator alone.