If/Else
This works pretty much the same as you expect but the expression doesn’t need to be surrounded by parentheses().
Compact If
We can also compact our if statements.This pattern is quite common.
Switch
Next, we haveswitch statement, which is often a shorter way to write conditional logic.
In Go, the switch case only runs the first case whose value is equal to the condition expression and not all the cases that follow. Hence, unlike other languages, break statement is automatically added at the end of each case.
This means that it evaluates cases from top to bottom, stopping when a case succeeds.
Let’s take a look at an example:
Fallthrough
We can also use thefallthrough keyword to transfer control to the next case even though the current case might have matched.
fallthrough keyword.
switch true.
Loops
Now, let’s turn our attention toward loops. So in Go, we only have one type of loop which is thefor loop.
But it’s incredibly versatile. Same as if statement, for loop, doesn’t need any parenthesis () unlike other languages.
For Loop
Let’s start with the basicfor loop.
for loop has three components separated by semicolons:
- init statement: which is executed before the first iteration.
- condition expression: which is evaluated before every iteration.
- post statement: which is executed at the end of every iteration.
Break and Continue
As expected, Go also supports bothbreak and continue statements for loop control. Let’s try a quick example:
continue statement is used when we want to skip the remaining portion of the loop, and break statement is used when we want to break out of the loop.
Also, Init and post statements are optional, hence we can make our for loop behave like a while loop as well.
We can also remove the additional semi-colons to make it a little cleaner.