|A Programmer's Guide To Go With LiteIDE|
|Written by Mike James|
|Thursday, 14 November 2013|
Page 4 of 4
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 Programmer's Guide To Go
To be informed about new articles on I Programmer, install the I Programmer Toolbar, subscribe to the RSS feed, follow us on, Twitter, Facebook, Google+ or Linkedin, or sign up for our weekly newsletter.
or email your comment to: email@example.com
|Last Updated ( Thursday, 04 July 2019 )|