|A Programmer's Guide To Go With Visual Studio Code|
|Written by Mike James|
|Monday, 08 July 2019|
Page 5 of 5
You can leave out any of the components of the for statement but you have to put the semicolons in to show which parts you are leaving out. The only exception to this rule is the condition which you can simply write without semi-colons to create the conditional form of the for.
You can also iterate through a range of values in an array, slice, string, map or channel. This is Go's equivalent of the for each loop in other languages.
The range form of the for loop iterates over the index and the value of sequences i.e. i and v in this case.
There are only two other control statements in Go. The if is much like it is in other languages but without the brackets around the condition. For example:
You don't have to use an else but you do need the curly brackets. For example:
You can create multiple if statements by following else with another if.
You can also include an initial statement which is executed before the if:
Any variables created are only in scope for the if statement.
There is also a switch statement for multiway selections on a single expression. For example
You can also write conditions on each of the case statements as in
There is no need to use break to jump out of a select but you do need to use fallthrough if you want cases to run into each other. The case statements are executed in order and the first one that succeeds causes a break - so the default has to be at the end in most cases.
As well as being able to write a select on values and conditions you can also write a switch on types. For example;
Finally there are the break and continue statements that can be used within a for loop to either terminate the loop or terminate the current iteration respectively. The break can also be used to jump out of a switch.
There is a goto, but this isn't worth talking about.
A Programmers Guide To Languages
or email your comment to: firstname.lastname@example.org
|Last Updated ( Monday, 08 July 2019 )|