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.

names := ["Sam", "Peter"] for i, name <- names { println i, name } m := {"one": 1, "two": 2} for key, val <- m { println key, val } for key, _ <- m { println key } for val <- names { println val } for val <- m { println val }

2、Range for

You can use range expression (start:end:step) in for loop.

for i <- :5 { println i } for i <- 1:5 { println i } for i <- 1:5:2 { println i }

3、for/<-/if

All loops of for/<- form can have an optional if condition.

numbers := [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] for num <- numbers if num%3 == 0 { println num } for num <- :10 if num%3 == 0 { println num }

4、Condition for

The condition can be omitted, resulting in an infinite loop. You can use break or return to end the loop.

sum := 0 i := 1 for i <= 100 { sum += i i++ } println sum for { if sum > 0 { break } }

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.

for i := 0; i < 10; i += 2 { if i == 6 { continue } println i }

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.

for i := 1; i <= 100; i++ { if i%3 == 0 && i%5 == 0 { println("FizzBuzz") continue } if i%3 == 0 { println("Fizz") continue } if i%5 == 0 { println("Buzz") break } println(i) }

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”

samples := []string{"hello", "apple_π!"} outer: for _, sample := range samples { for i, r := range sample { println(i, r, string(r)) if r == 'l' { continue outer } } println() }

Next example: Arrays