Control Structures
Go has fewer control structures than languages like C or Java, but they are versatile.If / Else
The syntax is similar to C, but parentheses() are not required around the condition, and braces {} are mandatory.
If with Short Statement
You can execute a short statement before the condition. Variables declared here are scoped to theif block.
For Loops
Go has only one looping construct: thefor loop. It can be used in three ways.
1. Standard C-style Loop
2. While-style Loop
If you omit the init and post statements, it acts like awhile loop.
3. Infinite Loop
If you omit the condition, it loops forever.Switch Statements
Go’sswitch is more powerful than in C.
- No
breakneeded (it’s implicit). - Cases don’t need to be constants or integers.
Switch with no condition
This is a clean way to write long if-then-else chains.Defer
Adefer statement defers the execution of a function until the surrounding function returns.
The deferred call’s arguments are evaluated immediately, but the function call is not executed until the surrounding function returns.