# Control Structures in Go
It is time to discuss control structures in Go. You will start with the if
statement.
# if
statement
The syntax is as follows:
You need brackets {}
for each if
statement. The {
bracket needs to be on the same line as the if
statement.
If you want to use an else if
or else
statement, note that they have to be on the same line as the }
bracket of the previous block.
You can also give if
or else if
a short statement to execute before the condition:
Boolean expressions evaluate for true
or false
. The comparison operators are:
The if
statement is also used for error handling. You will often see code like:
# switch
statement
The syntax of a switch
statement is as follows:
Cases are evaluated from top to bottom. The switch
finishes if a case
succeeds.
values_x
must have the same type as expression
.
If you do not give an expression to switch
, then Go interprets it as switch true
. This provides another way to write if-else if-else
chains:
Unlike other languages (for example C), you do not need to break
to avoid fallthrough. In Go, you need to fallthrough
explicitly. fallthrough
will enter the next case, even if the expression does not match.
There are so-called type switches in Go:
You can use multiple value cases, like case 1, 2, 4, 9, 16:
.
# for
statement
for
is the only looping statement in Go. The syntax is as follows:
Before the iterations start, it will first execute the init_statement
. The loop body will be executed as long as condition_expression
is true. The post_statement
will be executed at the end of every iteration.
init_statement
and post_statement
are optional. Without them, the for
statement is like the while
statement in other languages.
You can use continue
to skip the iteration or break
to terminate the execution, like in C, C#, Java, etc.
Further reading:
To summarize, this section has explored:
- Control structures in Go, and the syntax used by the
if
statement, theswitch
statement, and thefor
statement. - How unlike other languages Go does not need to
break
to avoid fallthrough, instead you need to provide thefallthrough
instruction explicitly.