For
The For statement consists of three basic parts, separated by semicolons:
- Initial statement: Executes only before the start of the first loop, usually the variable definition and initialization, where the variables defined are scoped only to the for loop itself.
- Conditional expression: Every time the loop starts before it executes, when false ends the loop.
- Post statement: Executed at the end of each iteration.
Skills:
- The initial statement and the post statement can be omitted.
- Conditional expressions can also be omitted, which is a dead loop.
- The go language has only one loop structure, which is the for statement. The while statement is also represented by a for in go.
// forsum := 1for ; sum < 1000; { sum += sum}// whilesum := 1for sum < 1000 { sum += sum}
Note the point:
- Unlike other languages, three statements do not need to be enclosed in parentheses.
- The loop body needs to be enclosed in curly braces.
If
As with for, the IF statement can contain an initial statement scoped to the if itself (including else). Similarly, if statements do not require parentheses, but curly braces are required.
Switch
Switch is a better choice for if else statements in some scenarios. Match to a case equal to condition and execute, and then stop switch without an explicit break.
You can also have an initial statement.
The condition can be null, which indicates switch true.
Defer
Postpone execution until the surrounding functions are executed.
The deferred function is placed in the stack, so it follows the LIFO principle.
Application scenarios such as for cleaning actions, see: Https://blog.golang.org/defer-panic-and-recover
A Tour of Go:basics 2