Condition
For
Go has only one looping construct, the for
loop.
{% hint style="warning" %}
Unlike other languages like C, Java, or JavaScript there are no parentheses surrounding the three components of the for
statement and the braces { }
are always required.
{% endhint %}
The init and post statements are optional.
For is Go's "while"
At that point you can drop the semicolons: C's while
is spelled for
in Go.
Forever
If you omit the loop condition it loops forever, so an infinite loop is compactly expressed.
If
Go's if
statements are like its for
loops; the expression need not be surrounded by parentheses ( )
but the braces { }
are required.
If with a short statement
Like for
, the if
statement can start with a short statement to execute before the condition.
Variables declared by the statement are only in scope until the end of the if
.
If and else
Variables declared inside an if
short statement are also available inside any of the else
blocks.
(Both calls to pow
return their results before the call to fmt.Println
in main
begins.)
Switch
A switch
statement is a shorter way to write a sequence of if - else
statements. It runs the first case whose value is equal to the condition expression.
Go's switch is like the one in C, C++, Java, JavaScript, and PHP, except that Go only runs the selected case, not all the cases that follow. In effect, the break
statement that is needed at the end of each case in those languages is provided automatically in Go. Another important difference is that Go's switch cases need not be constants, and the values involved need not be integers.
There is no automatic fall through, but cases can be presented in comma-separated lists.
Switch evaluation order
Switch cases evaluate cases from top to bottom, stopping when a case succeeds.
For example,
does not call f
if i==0
.
Switch with no condition
Switch without a condition is the same as switch true
.
{% hint style="info" %} This construct can be a clean way to write long if-then-else chains. {% endhint %}