For
For loop
Go+ has only one looping keyword: for, with several forms.
1、for/<-
This is the most common form. You can use it with a slice, map, numeric range or custom iterators.
The for value <- arr/map form is used for going through elements of a slice or a map.
If an index is required, an alternative form for index, value <- arr can be used.
2、Range for
You can use range expression (start:end:step) in for loop.
3、for/<-/if
All loops of for/<- form can have an optional if condition.
4、Condition for
The condition can be omitted, resulting in an infinite loop. You can use break or return to end the loop.
5、C for
Finally, there’s the traditional C style for loop. It’s safer than the while form because with the latter it’s easy to forget to update the counter and get stuck in an infinite loop.
break and continue
How do you get out of an infinite for loop without using the keyboard or turning off your computer? That’s the job of the break statement. It exits the loop immediately, just like the break statement in other languages. Of course, you can use break with any for statement, not just the infinite for statement.
Go+ also includes the continue keyword, which skips over rest of the body of a for loop and proceeds directly to the next iteration. Technically, you don’t need a continue statement.
Labeling Your “for” Statements
By default, the break and continue keywords apply to the for loop that directly contains them. What if you have nested for loops and you want to exit or skip over an iterator of an outer loop? Let’s look at an example. We’re going to modify our string iterating program to stop iterating through a string as soon as it hits a letter “l”
Next example: Arrays