Introduction#
Control statement categories:
- Sequential structure
- Branching structure
- Loop structure
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
- () can be added on both sides of the condition expression, but it is recommended not to add them.
- There must be a space between If and the condition expression.
- {} 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
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: